import 'dart:async';

import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:reabampos/src/reabam/operation/bean/api_upload_order_task.dart';
import 'package:reabampos/src/reabam/operation/bean/bean_paytype.dart';
import 'package:reabampos/src/reabam/operation/bean/bean_retry_order.dart';
import 'package:reabampos/src/reabam/operation/bean/h5_search_good.dart';
import 'package:reabampos/src/reabam/operation/bean/h5_upload_order.dart';
import 'package:reabampos/src/reabam/operation/bean/request_cuxiao.dart';
import 'package:reabampos/src/reabam/operation/bean/response_cuxiao.dart';
import 'package:reabampos/src/reabam/operation/rb_config.dart';
import 'package:reabampos/src/reabam/operation/rb_api.dart';
import 'package:reabampos/src/reabam/ui/pagestate_main_webview.dart';
import 'package:reabampos/src/reabam/utils/brean/c_bean_good_item.dart';
import 'package:reabampos/src/reabam/utils/rb_aliyun_log.dart';
import 'package:reabampos/src/reabam/utils/rb_business.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_aliyun_log.dart';
import 'package:xsdk_flutter/xsdk/xsdk_flutter_package.dart';

// 通过 `flutter pub run build_runner build`  生成的objectbox.g.dart
import '../../../../objectbox.g.dart';
import 'models.dart';
import 'models_cuxiao.dart';
import 'models_upload_order_task.dart';


typedef XFunctionObjectBoxCallback = void Function(Map<String,dynamic> result);

/*
flutter pub run build_runner build
 */
class XObjectBoxUtils {
  //在生成的objectbox.g.dart内
  static Store? store;

  static Box<BeanOfflineDBGood>? goodBox;
  static Box<BeanOfflineDBGoodSpec>? goodSpecBox;
  static Box<BeanShoppingCartDBGood>? shoppingCartDBGoodBox;
  static Box<BeanShoppingCartDBGoodSpec>? shoppingCartDBGoodSpecBox;
  static Box<BeanOfflineDBOrder>? orderBox;
  static Box<BeanOfflineDBPendingOrder>? pendingOrderBox;
  static Box<TestDBItem>? testItemBox;
  static Box<BeanShelfTime>? shelfTimeBox;

  static Box<BeanUploadOrderTask>? uploadOrderTaskBox;
  static Box<BeanUploadOrderDetail>? uploadOrderDetailBox;
  static Box<BeanUploadOrderShoppingCart>? uploadOrderShoppingCartBox;

  static Box<DbCXItemBomProduct>? box_DbCXItemBomProduct;
  static Box<DbCXItemTimed>? box_DbCXItemTimed;
  static Box<DbCXMutexPlan>? box_DbCXMutexPlan;
  static Box<DBCXOrderProduct>? box_DBCXOrderProduct;
  static Box<DbCXProduct>? box_DbCXProduct;
  static Box<DbCXPromotion>? box_DbCXPromotion;
  static Box<DbCXSuitBom>? box_DbCXSuitBom;
  static Box<BeanOfflinePay>? box_BeanOfflinePay;

  XObjectBoxUtils._create() {
    // 初始化各个实体类对应box,等同: Box<BeanOfflineDBGood>(store!);
    goodBox=store?.box<BeanOfflineDBGood>();
    goodSpecBox=store?.box<BeanOfflineDBGoodSpec>();
    shoppingCartDBGoodBox=store?.box<BeanShoppingCartDBGood>();
    shoppingCartDBGoodSpecBox=store?.box<BeanShoppingCartDBGoodSpec>();
    shelfTimeBox=store?.box<BeanShelfTime>();
    orderBox=store?.box<BeanOfflineDBOrder>();
    pendingOrderBox=store?.box<BeanOfflineDBPendingOrder>();
    testItemBox=store?.box<TestDBItem>();
    uploadOrderTaskBox=store?.box<BeanUploadOrderTask>();
    uploadOrderDetailBox=store?.box<BeanUploadOrderDetail>();
    uploadOrderShoppingCartBox=store?.box<BeanUploadOrderShoppingCart>();

    box_DbCXItemBomProduct=store?.box<DbCXItemBomProduct>();
    box_DbCXItemTimed=store?.box<DbCXItemTimed>();
    box_DbCXMutexPlan=store?.box<DbCXMutexPlan>();
    box_DBCXOrderProduct=store?.box<DBCXOrderProduct>();
    box_DbCXProduct=store?.box<DbCXProduct>();
    box_DbCXPromotion=store?.box<DbCXPromotion>();
    box_DbCXSuitBom=store?.box<DbCXSuitBom>();
    box_BeanOfflinePay=store?.box<BeanOfflinePay>();
  }

  /*
  1.初始化,可在app中初始化,或者在登录后调用接口获得对应的id使用不同的数据库
  //已在app中初始化WidgetsFlutterBinding.ensureInitialized();
  如:
  await XObjectBoxUtils.create(dbname);
   */


  static Future<XObjectBoxUtils> create(XPageState pageState,String dbName) async {

    XLogUtils.printLog('---XObjectBoxUtils,create');
    if(store!=null){
      store!.close();
      store=null;
    }

    final docsDir = await getApplicationDocumentsDirectory();
    //在生成的objectbox.g.dart内
    store = await openStore(
      directory: p.join(docsDir.path, dbName),
      macosApplicationGroup: 'FGDTDLOBXDJ.demo',//用于macOS沙箱
    );

    if(store==null){
      XLogUtils.printLog('---dbstore==null');
      pageState.toast('数据未能初始化!');

      if(XFlutterUtils.isAndroid()){
        XFlutterUtils.restartApp();
      }

    }else{
      XLogUtils.printLog('---dbstore!=null');
    }


    return XObjectBoxUtils._create();
  }


  ///////////////////////////////////////////////////////////////////////

  static void saveBeanOfflineDBGood(BeanOfflineDBGood item){
    goodBox!.put(item);
  }
  static void saveBeanOfflineDBGoodSpec(BeanOfflineDBGoodSpec item){
    goodSpecBox!.put(item);
  }

  static BeanOfflineDBGood? getBeanOfflineDBGoodById(int id) {
    return goodBox!.get(id);
  }


  static void getBeanOfflineDBGoodList(
      {
        required int pageIndex,
        required int pageSize,
        String? fCode,
        String? keyword,
        required bool isFixBarcodeRule,
        required int ruleType,
        required String amount,
        required String weight,
        required int reverseDecimalCount,
        required int amountDecimalCount,
        required int weightDecimalCount,
        bool isSearchMainItem=true, //默认搜索返回主商品(单规格商品,多规格主商品)
        required XFunctionObjectBoxCallback callback
      }
      ) {

    Future((){
      ItemListResponse response =ItemListResponse();
      response.code="-1";

      List<Map<String,dynamic>> h5JsonList=[];

      try{

        //总页数
        int pageCount=0;
        //总商品数
        int totalCount=0;

        List<BeanOfflineDBGood> list=[];

        if(isFixBarcodeRule && !XStringUtils.isEmpty(keyword)) {
          //搜索匹配金额码,重量码
          XLogUtils.printLog('---搜索匹配金额码,重量码');
          //
          QueryBuilder<BeanOfflineDBGood> queryBuilder=goodBox!.query(
              BeanOfflineDBGood_.isDel.equals(false).andAll(
                  [
                    BeanOfflineDBGood_.skuBarcode.equals(keyword!),
                    _handleShelfValidity()
                  ]
              )
          );
          Query<BeanOfflineDBGood> query =_handleShelfTime(queryBuilder);
          totalCount=query.count();
          XLogUtils.printLog('---搜索匹配金额码,重量码,totalCount=$totalCount');

          if(totalCount==0){
            response.msg="没有匹配到,请联系管理员";
          }else if(totalCount>1){
            response.msg="匹配到多个,请联系管理员";
          }else{
            // =1时
            list = query.find();
            query.close();

            for (BeanOfflineDBGood sItem in list){
              Map<String,dynamic> m=XJsonUtils.json2Map(sItem.json);
              h5JsonList.add(m);
            }

            Map<String,dynamic> m=h5JsonList.first;

            double dAmount=0;
            double itemQty=-1;

            try{

              if(ruleType==5){
                //条码金额码+重量码 5
                if(weightDecimalCount==0){
                  itemQty= XNumberUtils.d2d(0,double.tryParse(weight)??0/1000);
                }else{
                  itemQty= XNumberUtils.d2d(weightDecimalCount,double.tryParse(weight)??0/1000);
                }

                XLogUtils.printLog('---itemQty=$itemQty,weight=$weight,double.tryParse(weight)=${double.tryParse(weight)}');

                if(amountDecimalCount==0){
                  dAmount= XNumberUtils.d2d(0,double.tryParse(amount)??0/100);
                }else{
                  dAmount= XNumberUtils.d2d(amountDecimalCount,double.tryParse(amount)??0/100);
                }

              }else if(ruleType==3){
                //条码金额码 3
                double dspecPrice = m['dealPrice']==null?0:double.tryParse(m['dealPrice'].toString())??0;

                dAmount= XNumberUtils.d2d(2,double.tryParse(amount)??0/100);
                if(dspecPrice!=0){
                  itemQty = XNumberUtils.d2d(reverseDecimalCount,dAmount / dspecPrice);
                }

              }else if(ruleType==2){
                //条码重量码 2
                double dspecPrice = m['dealPrice']==null?0:double.tryParse(m['dealPrice'].toString())??0;

                itemQty = XNumberUtils.d2d(3,double.tryParse(amount)??0 / 1000);
                dAmount = XNumberUtils.d2d(2,itemQty * dspecPrice);

              }


              if (itemQty <= 0){
                response.msg="商品金额异常,不能添加商品";
              }else{
                response.code="200";

                m['type']=ruleType;
                m["reverseDecimalCount"]=reverseDecimalCount;
                m["price"]=dAmount;
                m["quantity"]=itemQty;
                m["skuBarcode"]=keyword;
                response.codeData=m;

              }

            }catch (e){
              XLogUtils.printLog('---处理金额码重量码,报错:$e');
              response.msg="处理金额码重量码,不能添加商品";
            }
          }

        }else{
          //普通搜索,非重量码金额码,
          XLogUtils.printLog('---非重量码金额码搜索');

          if (pageIndex<0||pageSize<=0){
            callback(response.toJson());
            return;
          }

          if (XStringUtils.isEmpty(keyword)){

            if (XStringUtils.isEmpty(fCode)){

              //计算分页,总商品数
              totalCount=goodBox!.count()??0;
              if (totalCount/pageSize==0){
                pageCount=1;
              }else{
                pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
              }
              //偏离数=当前页数(第一页从1开始)*每页数量
              int offset=(pageIndex-1)*pageSize;

              //全部分类
              QueryBuilder<BeanOfflineDBGood> queryBuilder=goodBox!.query(
                  BeanOfflineDBGood_.isDel.equals(false).and(_handleShelfValidity())
              );
              Query<BeanOfflineDBGood> query =_handleShelfTime(queryBuilder);
              query.limit=pageSize;
              query.offset=offset;
              list = query.find();
              query.close();

            }else{
              //按分类  同一张分类表支持多层,用contains,不用equal
              QueryBuilder<BeanOfflineDBGood> queryBuilder=goodBox!.query(
                  BeanOfflineDBGood_.isDel.equals(false).andAll(
                      [
                        BeanOfflineDBGood_.itemTypefCode.contains(fCode!),
                        _handleShelfValidity()
                      ]
                  )
              );
              Query<BeanOfflineDBGood> query =_handleShelfTime(queryBuilder);

              //计算分页,总商品数
              totalCount=query.count();
              if (totalCount/pageSize==0){
                pageCount=1;
              }else{
                pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
              }
              //偏离数=当前页数(第一页从1开始)*每页数量
              int offset=(pageIndex-1)*pageSize;

              query.limit=pageSize;
              query.offset=offset;
              list = query.find();
              query.close();

            }

          }else{
            //全部分类,优先精准查询
            XLogUtils.printLog('---全部分类,优先精准查询单规格商品');
            QueryBuilder<BeanOfflineDBGood> queryBuilder=goodBox!.query(
                BeanOfflineDBGood_.isDel.equals(false).andAll(
                    [
                      BeanOfflineDBGood_.itemId.equals(keyword!).orAny(
                          [
                            BeanOfflineDBGood_.skuBarcode.equals(keyword),
                            BeanOfflineDBGood_.attachBarcode.equals(keyword),
                          ]
                      ),
                      _handleShelfValidity()
                    ]
                )
            );
            Query<BeanOfflineDBGood> query =_handleShelfTime(queryBuilder);
            totalCount=query.count();
            XLogUtils.printLog('---精确查询单规格商品itemId,skuBarcode,attachBarcode,totalCount=$totalCount');

            if(!isSearchMainItem){
              //精确搜索返回到规格
              if(totalCount==0){
                QueryBuilder<BeanOfflineDBGood> queryBuilder1=goodBox!.query(
                    BeanOfflineDBGood_.isDel.equals(false).andAll(
                        [
                          BeanOfflineDBGood_.skuBarcode.contains(keyword),
                          _handleShelfValidity()
                        ]
                    )
                );
                query =_handleShelfTime(queryBuilder1);
                int totalCount_temp=query.count();
                if(totalCount_temp!=0){
                  //查规格
                  List<BeanOfflineDBGood> list_temp = query.find();
                  for(BeanOfflineDBGood iitem in list_temp){

                    Query<BeanOfflineDBGoodSpec>? query_spec=goodSpecBox!.query(
                        BeanOfflineDBGoodSpec_.isDel.equals(false).andAll(
                          [
                            BeanOfflineDBGoodSpec_.itemId.equals(iitem.itemId??''),
                            BeanOfflineDBGoodSpec_.skuBarcode.equals(keyword)
                          ]
                        )
                    ).build();

                    if(query_spec.count()!=0){
                      BeanOfflineDBGoodSpec spec_temp=query_spec.findFirst()!;
                      iitem.specId=spec_temp.specId;
                      iitem.specName=spec_temp.specName;
                      iitem.skuBarcode=spec_temp.skuBarcode;
                      iitem.attachBarcode=spec_temp.attachBarcode;
                      //
                      Map<String,dynamic> specM=XJsonUtils.json2Map(spec_temp.json);
                      specM['itemId']=iitem.itemId;
                      specM['itemName']=iitem.itemName;
                      specM['specType']=iitem.specType;
                      iitem.json=XJsonUtils.obj2Json(specM);

                      //返回规格商品
                      list.add(iitem);
                      totalCount=list.length;

                      query_spec.close();
                      break;
                    }

                    query_spec.close();
                  }

                }

                XLogUtils.printLog('---精确查询多规格商品skuBarcode, totalCount=$totalCount');
              }
            }

            if(totalCount==0){
              QueryBuilder<BeanOfflineDBGood> queryBuilder1=goodBox!.query(
                  BeanOfflineDBGood_.isDel.equals(false).andAll(
                      [
                        BeanOfflineDBGood_.itemName.contains(keyword).orAny(
                            [
                              BeanOfflineDBGood_.itemCode.contains(keyword),
                              BeanOfflineDBGood_.pinyin.contains(keyword.toLowerCase())
                            ]
                        ),
                        _handleShelfValidity()
                      ]
                  )
              );
              query =_handleShelfTime(queryBuilder1);
              totalCount=query.count();
              XLogUtils.printLog('---模糊查询,totalCount=$totalCount');
            }


            if(list.isEmpty){//没有精确到返回规格的情况
              //计算分页,总商品数
              if (totalCount/pageSize==0){
                pageCount=1;
              }else{
                pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
              }
              //偏离数=当前页数(第一页从1开始)*每页数量
              int offset=(pageIndex-1)*pageSize;

              query.limit=pageSize;
              query.offset=offset;
              list = query.find();
              query.close();
            }

          }

          //
          for (BeanOfflineDBGood sItem in list){
            Map<String,dynamic> m=XJsonUtils.json2Map(sItem.json);

            List<Map<String,dynamic>> itemtimepromotions=getTejiaPromotions('${m["itemId"]}');
            m["itemtimepromotions"]=itemtimepromotions;

            h5JsonList.add(m);
          }

          response.code="200";
          response.msg='';
          response.PageIndex=pageIndex;
          response.PageCount=pageCount;
          response.totalCount=totalCount;

        }

        response.items=h5JsonList;
        callback(response.toJson());

      }catch(e){
        XLogUtils.printLog('$e');
        response.code="-1";
        callback(response.toJson());
      }
    });

  }

  static ItemListResponse getGoodItems_simpleJson(
      {
        required int pageIndex,
        required int pageSize,
        String? fCode,
        String? keyword,
      }
      ) {

    ItemListResponse response =ItemListResponse();

    try{

      if (pageIndex<0||pageSize<=0){
        response.code="-1";
        return response;
      }

      //总页数
      int pageCount=0;
      //总商品数
      int totalCount=0;

      List<BeanOfflineDBGood> list=[];

      if (XStringUtils.isEmpty(keyword)){

        if (XStringUtils.isEmpty(fCode)){

          //计算分页,总商品数
          totalCount=goodBox!.count()??0;
          if (totalCount/pageSize==0){
            pageCount=1;
          }else{
            pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
          }
          //偏离数=当前页数(第一页从1开始)*每页数量
          int offset=(pageIndex-1)*pageSize;

          //全部分类
          QueryBuilder<BeanOfflineDBGood> queryBuilder=goodBox!.query(
              BeanOfflineDBGood_.isDel.equals(false).and(_handleShelfValidity())
          );
          Query<BeanOfflineDBGood> query =_handleShelfTime(queryBuilder);
          query.limit=pageSize;
          query.offset=offset;
          list = query.find();
          query.close();

        }else{
          //按分类  同一张分类表支持多层,用contains,不用equal
          QueryBuilder<BeanOfflineDBGood> queryBuilder=goodBox!.query(
              BeanOfflineDBGood_.isDel.equals(false).andAll(
                  [
                    BeanOfflineDBGood_.itemTypefCode.contains(fCode!),
                    _handleShelfValidity()
                  ]
              )
          );
          Query<BeanOfflineDBGood> query =_handleShelfTime(queryBuilder);
          //计算分页,总商品数
          totalCount=query.count();
          if (totalCount/pageSize==0){
            pageCount=1;
          }else{
            pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
          }
          //偏离数=当前页数(第一页从1开始)*每页数量
          int offset=(pageIndex-1)*pageSize;

          query.limit=pageSize;
          query.offset=offset;
          list = query.find();
          query.close();

        }

      }else{
        //全部分类,优先精确查询
        QueryBuilder<BeanOfflineDBGood> queryBuilder=goodBox!.query(
            BeanOfflineDBGood_.isDel.equals(false).andAll(
                [
                  BeanOfflineDBGood_.skuBarcode.equals(keyword!).orAny(
                      [
                        BeanOfflineDBGood_.itemId.equals(keyword),
                        BeanOfflineDBGood_.attachBarcode.equals(keyword)
                      ]
                  ),
                  _handleShelfValidity()
                ]
            )
        );
        Query<BeanOfflineDBGood> query =_handleShelfTime(queryBuilder);
        totalCount=query.count();
        XLogUtils.printLog('---精确查询,totalCount=$totalCount');

        if(totalCount==0){
          QueryBuilder<BeanOfflineDBGood> queryBuilder1=goodBox!.query(
              BeanOfflineDBGood_.isDel.equals(false).andAll(
                  [
                    BeanOfflineDBGood_.itemName.contains(keyword).orAny(
                        [
                          BeanOfflineDBGood_.skuBarcode.contains(keyword),
                          BeanOfflineDBGood_.itemCode.contains(keyword),
                          BeanOfflineDBGood_.pinyin.contains(keyword.toLowerCase())
                        ]
                    ),
                    _handleShelfValidity()
                  ]
              )
          );
          query =_handleShelfTime(queryBuilder1);
          totalCount=query.count();
          XLogUtils.printLog('---模糊查询,totalCount=$totalCount');
        }

        //计算分页,总商品数
        if (totalCount/pageSize==0){
          pageCount=1;
        }else{
          pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
        }
        //偏离数=当前页数(第一页从1开始)*每页数量
        int offset=(pageIndex-1)*pageSize;

        query.limit=pageSize;
        query.offset=offset;
        list = query.find();
        query.close();
      }

      //
      List<Map<String,dynamic>> h5JsonList=[];

      for (BeanOfflineDBGood sItem in list){
        Map<String,dynamic> m=XJsonUtils.json2Map(sItem.jsonSimple);
        m['shelfValidityStart']=sItem.shelfValidityStart;
        m['shelfValidityEnd']=sItem.shelfValidityEnd;
        m['shelfTime']=sItem.shelfTime;
        m['version']=sItem.version;
        //XLogUtils.printLog('-------sItem=${sItem.itemName},lineId=${sItem.lineId},version=${sItem.version}');
        h5JsonList.add(m);
      }

      response.code="200";
      response.msg='1213';
      response.PageIndex=pageIndex;
      response.PageCount=pageCount;
      response.totalCount=totalCount;
      response.items=h5JsonList;

    }catch(e){
      XLogUtils.printLog('$e');
      response.code="-1";
    }

    return response;

  }


  //接入处理上架日期
  static Condition<BeanOfflineDBGood> _handleShelfValidity(){
    //当前日期
    int currentTimeLong=XDateUtils.getCurrentTime_ms();
    return BeanOfflineDBGood_.shelfValidityStart.lessOrEqual(currentTimeLong).and(
        BeanOfflineDBGood_.shelfValidityEnd.equals(0).or(
            BeanOfflineDBGood_.shelfValidityEnd.greaterOrEqual(currentTimeLong)
        )
    );
  }

  //接入处理上架时间段
  static Query<BeanOfflineDBGood> _handleShelfTime(QueryBuilder<BeanOfflineDBGood> queryBuilder){
    //当前时间
    int hour=int.parse(XDateUtils.getCurrentTime_String(format: 'HH'))*60*60*1000;
    int min=int.parse(XDateUtils.getCurrentTime_String(format: 'mm'))*60*1000;
    int h_m=hour+min;

    queryBuilder.linkMany(
        BeanOfflineDBGood_.shelfTime,
        BeanShelfTime_.shelfTimeStart.lessOrEqual(h_m).and(
            BeanShelfTime_.shelfTimeEnd.equals(0).or(BeanShelfTime_.shelfTimeEnd.greaterOrEqual(h_m))
        )
    );
    //
    queryBuilder.order(BeanOfflineDBGood_.lineId);

    return queryBuilder.build();
  }


  static void getTestShelfValidity(){
    String s1='2024-08-02 00:00:00';
    int currentTimeLong=XDateUtils.getTime_ms(dateTime:XDateUtils.getDateTimeWithString(s1));
    int h_m=14*60*60*1000+35*60*1000;

    int totalCount=goodBox!.count();
    int totalshelfTimeCount=shelfTimeBox!.count();
    XLogUtils.printLog('---totalCount=$totalCount,totalshelfTimeCount=$totalshelfTimeCount');

    QueryBuilder<BeanOfflineDBGood> queryBuilder = goodBox!.query(
        BeanOfflineDBGood_.isDel.equals(false).and(
            BeanOfflineDBGood_.shelfValidityStart.lessOrEqual(currentTimeLong).and(
                BeanOfflineDBGood_.shelfValidityEnd.equals(0).or(BeanOfflineDBGood_.shelfValidityEnd.greaterOrEqual(currentTimeLong)
                )
            )
        )
    );
    //
    queryBuilder.linkMany(
        BeanOfflineDBGood_.shelfTime,
        BeanShelfTime_.shelfTimeStart.lessOrEqual(h_m).and(
            BeanShelfTime_.shelfTimeEnd.equals(0).or(BeanShelfTime_.shelfTimeEnd.greaterOrEqual(h_m))
        )
    );
    //
    queryBuilder.order(BeanOfflineDBGood_.lineId);


    //
    Query<BeanOfflineDBGood> query=queryBuilder.build();
    int count=query.count();
    XLogUtils.printLog('---count=$count');
    BeanOfflineDBGood? item=query.findFirst();
    XLogUtils.printLog('---item=${item?.shelfValidityStart}');
    //


  }

  static void getGoodItemDetail(
      {
        required String itemId,//支持sku传入
        required XFunctionObjectBoxCallback callback
      }
      ) {

    Future((){
      ItemDetailResponse response =ItemDetailResponse();
      response.code="-1";

      try{

        //全部分类
        Query<BeanOfflineDBGood> query =goodBox!
            .query(BeanOfflineDBGood_.isDel.equals(false).and(
            BeanOfflineDBGood_.itemId.contains(itemId)
                .or(BeanOfflineDBGood_.skuBarcode.contains(itemId))
        )
        ).order(BeanOfflineDBGood_.lineId).build();

        BeanOfflineDBGood? sItem = query.findFirst();
        query.close();

        if(sItem!=null){
          Map<String,dynamic> m=XJsonUtils.json2Map(sItem.json);

          List<Map<String,dynamic>> itemtimepromotions=getTejiaPromotions('${m["itemId"]}');
          XLogUtils.printLog('---商品详情itemtimepromotions=${XJsonUtils.obj2Json(itemtimepromotions)}');
          m["itemtimepromotions"]=itemtimepromotions;//itemtimepromotions

          response.code="200";
          response.item=m;
        }

        callback(response.toJson());

      }catch(e){
        XLogUtils.printLog('$e');
        response.code="-1";
        callback(response.toJson());
      }
    });

  }

  //特价
  static List<Map<String,dynamic>> getTejiaPromotions(String? specId){
    List<Map<String,dynamic>> list=[];

    if(!XStringUtils.isEmpty(specId)){

      //A.查找商品拥有的促销
      Set<String> planIds={};
      Query<DbCXProduct> queryProduct =box_DbCXProduct!.query(
          DbCXProduct_.productType.equals('-1')
              .and(DbCXProduct_.typeId.equals(specId!)
              .and(DbCXProduct_.excl.equals(false)
          ))).build();

      List<DbCXProduct> listProduct=queryProduct.find();
      XLogUtils.printLog("---商品拥有的促销=${XJsonUtils.obj2Json(listProduct)}, size=${listProduct.length}");
      for (DbCXProduct product in listProduct){
        planIds.add(product.planIdEach??'');
      }


      //B.促销规则json
      Query<DbCXPromotion> queryPromotion =box_DbCXPromotion!.query(
          DbCXPromotion_.planType.equals('P005')
              .and(DbCXPromotion_.planId.oneOf(planIds.toList())
          )).build();

      List<DbCXPromotion> listPromotion=queryPromotion.find();
      //
      List<BeanShoppingCartItemPromotionJson> listBeanshoppingcartitempromotionjson=[];
      for(DbCXPromotion iitem in listPromotion){
        //按时间过滤
        bool isInTime=true;
        String beginDate=iitem.beginDate??'';
        String endDate=iitem.endDate??'';
        if(!XStringUtils.isEmpty(beginDate) && !XStringUtils.isEmpty(endDate)){
          //init
          isInTime=false;
          try{
            int startTime=int.tryParse(beginDate)??0;
            int endTime=int.tryParse(endDate)??0;
            int now=XDateUtils.getCurrentTime_ms();
            if(now>=startTime && now<=endTime){
              isInTime=true;
            }
          }catch (e){
            XLogUtils.printLog('---解析startTime/endTime报错:$e');
          }
        }

        if(isInTime){
          //在有效时间内
          BeanShoppingCartItemPromotionJson itemPromotionJson= BeanShoppingCartItemPromotionJson();
          itemPromotionJson.projectId=iitem.projectId;
          itemPromotionJson.version=iitem.version;
          itemPromotionJson.planId=iitem.planId;
          itemPromotionJson.planType=iitem.planType;
          itemPromotionJson.promotion=XJsonUtils.json2Map(iitem.promotionJson);
          listBeanshoppingcartitempromotionjson.add(itemPromotionJson);
        }
      }
      /*
                    适配: 1.先插入增量后插入全量情况; 2.补低版本增量情况
                    避免增量删除了某些规则情况: 同一projectId,只取版本号高的
                     */
      //1.算出每个projectId的最高版本
      Map<String,int> projectidVersion={};
      for(BeanShoppingCartItemPromotionJson iitem in listBeanshoppingcartitempromotionjson){
        int? noteVersion=projectidVersion['${iitem.projectId}'];
        if(noteVersion==null){
          projectidVersion['${iitem.projectId}']=iitem.version;
        }else{
          if(noteVersion<iitem.version){
            projectidVersion['${iitem.projectId}']=iitem.version;
          }
        }
      }
      //2.清除每个projectId的低版本促销
      listBeanshoppingcartitempromotionjson.removeWhere((BeanShoppingCartItemPromotionJson element){
        int lastVersion=projectidVersion['${element.projectId}']??0;
        if(element.version<lastVersion){
          return true;
        }
        return false;
      });
      //3.去重
      Set<BeanShoppingCartItemPromotionJson> setPromotionjson={};
      setPromotionjson.addAll(listBeanshoppingcartitempromotionjson);


      //C.秒杀规则
      for(BeanShoppingCartItemPromotionJson iitem in setPromotionjson){

        dynamic itemtimeds;

        dynamic promotions=iitem.promotion;
        String planidItemtimed=iitem.planId??'';


        Query<DbCXItemTimed> queryItemtimed =box_DbCXItemTimed!.query(
            DbCXItemTimed_.planId.equals(planidItemtimed))
            .order(DbCXItemTimed_.version,flags: Order.descending)
            .build();

        List<DbCXItemTimed> listItemtimed=queryItemtimed.find();
        //排序去重
        if (listItemtimed.isNotEmpty){
          itemtimeds =listItemtimed.first;
        }

        Map<String,dynamic> itemtimepromotion={};
        itemtimepromotion['promotions']=promotions;
        itemtimepromotion['itemtimeds']=itemtimeds;

        list.add(itemtimepromotion);

      }

    }

    XLogUtils.printLog("---特价list=${XJsonUtils.obj2Json(list)}");

    return list;
  }

//查找规格,第一页从1开始
  static void getSpecItemList(
      List<String>? specIds,
      XFunctionObjectBoxCallback callback
      ){

    Future((){

      ItemListResponse response =ItemListResponse();

      try{

        if (specIds==null||specIds.isEmpty){
          response.code="-1";
          callback(response.toJson());
          return;
        }

        //
        Query<BeanOfflineDBGoodSpec>? query;
        Condition<BeanOfflineDBGoodSpec>? condition;

        for (int i=0;i<specIds.length;i++){
          if (i==0){
            condition=BeanOfflineDBGoodSpec_.isDel.equals(false).and(BeanOfflineDBGoodSpec_.specId.equals(specIds[i]));
          }else{
            //叠加
            condition!.or(BeanOfflineDBGoodSpec_.specId.equals(specIds[i]));
          }

          if (i==(specIds.length-1)){
            //最后叠加
            query=goodSpecBox!.query(condition).order(BeanOfflineDBGoodSpec_.id)
                .build();
          }

        }

        List<BeanOfflineDBGoodSpec> list = query!.find();
        query.close();

        XLogUtils.printLog('---规格list=${XJsonUtils.obj2Json(list)}');

        //
        List<Map<String,dynamic>> h5JsonList=[];

        for (BeanOfflineDBGoodSpec sItem in list){
          Map<String,dynamic> m=XJsonUtils.json2Map(sItem.json);

          List<Map<String,dynamic>> itemtimepromotions=getTejiaPromotions('${m["specId"]}');
          m["itemtimepromotions"]=itemtimepromotions;

          h5JsonList.add(m);
        }

        response.code="200";
        response.PageIndex=1;
        response.PageCount=list.length;
        response.totalCount=1;
        response.items=h5JsonList;

        callback(response.toJson());

      }catch (e){
        XLogUtils.printLog('---getSpecItemList报错: $e');
        response.code='-1';
        callback(response.toJson());
      }

    });



  }

  static void getSpecItem(
      String specId,
      XFunctionObjectBoxCallback callback
      ){

    Future((){

      ItemListResponse response =ItemListResponse();

      try{

        if (XStringUtils.isEmpty(specId)){
          response.code="-1";
          callback(response.toJson());
          return;
        }

        //
        Query<BeanOfflineDBGoodSpec>? query=goodSpecBox!.query(
            BeanOfflineDBGoodSpec_.isDel.equals(false).and(BeanOfflineDBGoodSpec_.specId.equals(specId))
        ).order(BeanOfflineDBGoodSpec_.id)
            .build();

        List<BeanOfflineDBGoodSpec> list = query.find();
        query.close();

        XLogUtils.printLog('---规格item=${XJsonUtils.obj2Json(list)}');

        //
        List<Map<String,dynamic>> h5JsonList=[];

        for (BeanOfflineDBGoodSpec sItem in list){
          Map<String,dynamic> m=XJsonUtils.json2Map(sItem.json);
          List<Map<String,dynamic>> itemtimepromotions=getTejiaPromotions('${m["specId"]}');
          m["itemtimepromotions"]=itemtimepromotions;

          h5JsonList.add(m);
          break;
        }

        response.code="200";
        response.items=h5JsonList;

        callback(response.toJson());

      }catch (e){
        XLogUtils.printLog('---getSpecItem报错: $e');
        response.code='-1';
        callback(response.toJson());
      }

    });



  }


  //订单上传任务///////////////////////////////////////////////////////////////////////////

  //保存订单上传任务2.0, 开启事务
  static Map<String,dynamic> saveUploadOrderTaskByTransaction(
      Map<String,dynamic> itemH5,
      ){
    String? fastOrderNo=itemH5['fastOrderNo'];

    BeanUploadOrderH5Response response=BeanUploadOrderH5Response(
        code: "-1",
        msg: "新增上传任务2.0失败!",
        fastOrderNo: fastOrderNo
    );

    Map<String,dynamic> res;
    try{
      //重试失败任务,超过3次清零
      if(uploadFailedTaskList.isNotEmpty){
        for(BeanUploadOrderTask u in uploadFailedTaskList){
          if(!u.isFailedTaskUpLoading && u.failedTaskUploadCount>=3){
            u.failedTaskUploadCount=0;
          }
        }
      }
      //
      res= store?.runInTransaction(TxMode.write, (){
        return _saveUploadOrderTask2(itemH5);
      })??response.toJson();

    }catch (e){

      response.msg='$e';

      if(e is NumericOverflowException){
        //Thrown if a property query aggregate function (e.g. `sum()`) can not compute
      }else if(e is StorageException){
        //ObjectBox database exception with an OBX_ERROR code
        response.code='-2';
      }else if(e is DbFullException){
        //maxDBSizeInKB
        response.code='-2';
      }else if(e is DbMaxDataSizeExceededException){
        //maxDataSizeInKByte
      }else if(e is DbMaxReadersExceededException){
        //Thrown when the maximum amount of readers (read transactions) was exceeded. If a very high number of threads (>100) needs to be used, consider setting `maxReaders` when calling [Store.new].
      }else if(e is DbShutdownException){
        //Thrown when an error occurred that requires the store to be closed.
      }else if(e is UniqueViolationException){
        //A unique constraint would have been violated by this database operation.
      }else if(e is SchemaException){
        //Thrown when there is an error with the data schema (data model).
        //Typically, there is a conflict between the data model defined in your code
        //(using `@Entity` classes) and the data model of the existing database file.
      }else if(e is DbPagesCorruptException){
        // Errors related to pages were detected in a database file, e.g. bad page refs
        response.code='-2';
      }else if(e is DbFileCorruptException){
        //Errors were detected in a database file, e.g. illegal values or structural
        response.code='-2';
      }else if(e is NonUniqueResultException){
        //Thrown if `Query.findUnique()` is called, but the query matches more than one object.
      }else if(e is ObjectBoxException){
        //
      }
      XLogUtils.printLog('---saveUploadOrderTaskByTransaction新增上传任务2.0事务抛出错误,response.code=${response.code}, err= $e');
      //日志
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(fastOrderNo),'新增上传任务2.0事务抛出错误,response.code=${response.code}, err= $e');
      res=response.toJson();
    }

    return res;
  }

  //保存订单上传任务2.0
  static Map<String,dynamic> _saveUploadOrderTask2(
      Map<String,dynamic> itemH5){

    //
    BeanUploadOrderTask item=BeanUploadOrderTask();
    item.createDate=XDateUtils.getCurrentTime_String(format: XDateUtils.formatTimeDefault2);
    item.createDateLong=XDateUtils.getCurrentTime_ms();
    item.fastOrderNo=itemH5['fastOrderNo'];
    //对象转string保存
    item.pushJson=XJsonUtils.obj2Json(itemH5);
    BeanUploadOrderH5Response response=BeanUploadOrderH5Response(code: "200",msg: "添加新上传任务2.0!",fastOrderNo:item.fastOrderNo);

    //保存任务队列到数据库
    int id1 = uploadOrderTaskBox!.put(item);
    if(id1>0){
      //日志
      XLogUtils.printLog('---新增上传任务成功!');
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(item.fastOrderNo),'新增上传任务成功!');
    }else{
      XLogUtils.printLog('---新增上传任务失败!');
      //日志
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(item.fastOrderNo),'新增上传任务失败!');
    }

    //保存订单
    BeanUploadOrderDetail orderItem= BeanUploadOrderDetail();
    orderItem.fastOrderNo=item.fastOrderNo;
    orderItem.createDate=item.createDate;
    orderItem.createDateLong=item.createDateLong;
    orderItem.pushJson=item.pushJson;
    int id2 = uploadOrderDetailBox!.put(orderItem);
    if(id2>0){
      XLogUtils.printLog('---新增订单成功!');
      //日志
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(item.fastOrderNo),'新增订单成功!');
    }else{
      XLogUtils.printLog('---新增订单失败!');
      //日志
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(item.fastOrderNo),'新增订单失败!');
    }

    //上传订单,注意:这里逻辑是需要确认成功存入数据库才能发起上传,否则由h5发起上传
    Future((){
      _uploadOrderTaskX(item);
    });

    //通知h5
    return response.toJson();
  }

  //获得未上传订单数
  static int checkUnUploadOrderCnt(){

    int totalCount=0;
    try{
      totalCount=uploadOrderTaskBox!.count();
    }catch (e){
      XLogUtils.printLog('---getNotUploadOrderCount报错: $e');
    }

    return totalCount;

  }


  //h5检查订单是否已追平
  static void checkUploadOrder(String orderNo,XFunctionObjectBoxCallback callback){

    Future(() async {

      try{

        //检测本地未追平的单是否存在
        Query<BeanUploadOrderDetail> query=uploadOrderDetailBox!.query(
            BeanUploadOrderDetail_.fastOrderNo.equals(orderNo)
        ).build();
        List<BeanUploadOrderDetail> list=query.find();
        query.close();

        XLogUtils.printLog("---检测到本地单号:${list.length}");
        //已存在的单都是(触发点检测当时)未追平,现在需要重新检测
        if (list.isNotEmpty){
          BeanUploadOrderDetail orderItem=list.first;
          List<String> fastOrderNos=[];
          fastOrderNos.add(orderItem.fastOrderNo!);
          //
          Response_check_order? response = await RBBaseApi.checkOrderBusinessStatus(
            fastOrderNos:fastOrderNos,
          );

          if (response!=null){
            List<BeanCheckOrderData>? data=response.data;
            if (data!=null && data.isNotEmpty){
              BeanCheckOrderData iitem=data.first;
              if (iitem.businessSuccess
                  && orderItem.fastOrderNo == iitem.fastOrderNo
              ){
                //检测api已追平
                orderItem.businessSuccess=true;
                orderItem.orderId=iitem.orderId;

                XLogUtils.printLog("---businessSuccess:${orderItem.businessSuccess}");
                XLogUtils.printLog("---synSuccess:${iitem.synSuccess}");
                XLogUtils.printLog("---orderItem:${orderItem.orderId}");
                //通知h5
                callback(BeanUploadOrderH5Response(businessSuccess:true,orderId:orderItem.orderId,fastOrderNo:orderItem.fastOrderNo).toJson());

                //删除订单
                uploadOrderDetailBox!.remove(orderItem.id);

                //日志
                XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(orderNo),'检查(api)已追平删除本地订单!');
                return;
              }
            }
          }

          //检测api未追平
          callback(BeanUploadOrderH5Response(businessSuccess:false,orderId:orderItem.orderId,fastOrderNo:orderItem.fastOrderNo).toJson());
          //日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(orderNo),'检查(api)未追平!');

        }else{
          //本地不存在,则已追平,
          callback(BeanUploadOrderH5Response(businessSuccess:true,orderId:'',fastOrderNo:'').toJson());
          //日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(orderNo),'检查(api)是否追平,response返回没找到对应的orderNo');

        }

      }catch (e){
        XLogUtils.printLog('---saveUploadOrderTask报错: $e');
      }

    });


  }

  //保存订单购物车信息ok
  static void saveOrderShoppingcart(BeanH5UploadOrderTask itemH5,XFunctionObjectBoxCallback callback){

    Future((){
      try{
        //订单的购物车信息,保存到购物车临时表
        BeanUploadOrderShoppingCart shoppingcartItem=BeanUploadOrderShoppingCart();
        shoppingcartItem.fastOrderNo=itemH5.fastOrderNo;
        shoppingcartItem.pushJson=XJsonUtils.obj2Json(itemH5.pushJson);
        shoppingcartItem.createDate=XDateUtils.getCurrentTime_String(format: XDateUtils.formatTimeDefault2);
        shoppingcartItem.createDateLong=XDateUtils.getCurrentTime_ms();
        //保存
        uploadOrderShoppingCartBox!.put(shoppingcartItem);
        //
        callback(BeanUploadOrderH5Response(code: "200",msg: "保存购物车成功!").toJson());

      }catch (e){
        XLogUtils.printLog('---saveOrderShoppingcart报错: $e');
        //
        callback(BeanUploadOrderH5Response(code: "-1",msg: "保存购物车出错!").toJson());
      }
    });

  }

  //获得订单购物车 ok
  static void getOrderShoppingcart(String orderNo, XFunctionObjectBoxCallback callback){
    Future((){

      try{
        BeanUploadOrderH5Response2 response =BeanUploadOrderH5Response2();

        Query<BeanUploadOrderShoppingCart> query=
        uploadOrderShoppingCartBox!.query(BeanUploadOrderShoppingCart_.fastOrderNo.equals(orderNo))
            .order(BeanUploadOrderShoppingCart_.id,flags:Order.descending)
            .build();
        List<BeanUploadOrderShoppingCart> list=query.find();
        query.close();
        if (list.isEmpty){
          response.code="-1";
          response.msg="不存在该订单的购物车记录";
        }else{
          response.code="200";
          response.msg="成功";
          BeanUploadOrderShoppingCart item=list[0];

          Map<String, dynamic> m=XJsonUtils.json2Map(item.pushJson);
          m['createDate']=item.createDate;
          m['fastOrderNo']=item.fastOrderNo;
          response.orderId=item.fastOrderNo;
          response.data=m;
        }
        //
        callback(response.toJson());
      }catch (e){
        XLogUtils.printLog('---getOrderShoppingcart报错: $e');
        //
        callback(BeanUploadOrderH5Response2(code: "-1",msg: "获得购物车出错!").toJson());
      }

    });

  }



  //刷新订单,检测是否已追平 ok
  static void retryOrder(String orderNo,XFunctionObjectBoxCallback callback){
    Future(() async{
      try{
        //1.检测本地未追平的单任务是否存在
        List<BeanUploadOrderTask> listTask=uploadOrderTaskBox!.getAll();
        bool isHas=false;
        if (listTask.isNotEmpty){
          for (BeanUploadOrderTask taskItem in listTask){
            if (taskItem.fastOrderNo==orderNo){
              isHas=true;
              break;
            }
          }
        }

        if (isHas){
          //还存在该单的任务未上传,则没追平
          //通知完成更新
          callback(BeanRetryUploadOrderH5Response(code: "200",msg: "此单还有未上传任务!",retrySuccess: false).toJson());
        }else {
          //不存在该单未上传任务,则请求api重试
          List<String> fastOrderNos =[];
          fastOrderNos.add(orderNo);
          Response_retry_pos_order? response = await RBBaseApi.retryPosOrder(
              fastOrderNos:fastOrderNos,
              groupId:XSharePreferencesUtils.getString(RBConfigs.SP_groupId)
          );

          String? code;
          String? msg;
          bool retrySuccess=false;

          if (response != null) {
            code=response.code;
            msg=response.msg;

            List<BeanRetryData>? data = response.data;
            if (data != null && data.isNotEmpty) {
              BeanRetryData retryData = data[0];
              msg = retryData.retryResult;

              Query<BeanUploadOrderDetail> query = uploadOrderDetailBox!.query(BeanUploadOrderDetail_.fastOrderNo.equals(orderNo))
                  .build();
              List<BeanUploadOrderDetail> list2 = query.find();
              query.close();

              if (retryData.retrySuccess) {
                //
                retrySuccess = true;
                //追平,删除本地订单
                List<int> ids=[];
                for(BeanUploadOrderDetail detail in list2){
                  ids.add(detail.id);
                }
                uploadOrderDetailBox!.removeMany(ids);

                //日志
                XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(orderNo),'重试(api)已追平删除本地订单, response=${XJsonUtils.obj2Json(response)}');
              }else{
                //更新错误信息
                for(BeanUploadOrderDetail order in list2){
                  if (orderNo==order.fastOrderNo){
                    order.orderMsg=msg;
                  }
                }
                uploadOrderDetailBox!.putMany(list2);

                //日志
                XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(orderNo),'重试(api)未追平删除本地订单, response=${XJsonUtils.obj2Json(response)}');
              }
            }
          } else {
            code = "-1";
            msg='刷新订单出错!';
          }

          //通知完成更新
          callback(BeanRetryUploadOrderH5Response(code: code,msg: msg,retrySuccess: retrySuccess).toJson());
        }
      }catch (e){
        XLogUtils.printLog('---retryOrder报错: $e');
        //
        callback(BeanRetryUploadOrderH5Response(code: "-1",msg: "刷新订单出错!",retrySuccess: false).toJson());
      }

    });


  }


  //查找本地未追平订单(触发检测所有订单是否已追平) ok
  static void getUploadOrderList(BeanH5RequestPageLocalOrder request, XFunctionObjectBoxCallback callback){
    Future((){
      try{

        //0.重试失败任务,超过3次清零
        for(BeanUploadOrderTask u in uploadFailedTaskList){
          if(!u.isFailedTaskUpLoading && u.failedTaskUploadCount>=3){
            u.failedTaskUploadCount=0;
          }
        }
        reTryFailUploadTask();

        //1.触发检测所有订单是否已追平(已追平则删除)
        checkAndDeleteUploadOrder();

        //2.查找本地订单(未追平的订单)
        callback(_findUploadOrderList2(request));

      }catch (e){
        XLogUtils.printLog('---getUploadOrderList报错: $e');
      }
    });
  }


  //检测本地订单是否已追平(已追平则删除) ok
  static void checkAndDeleteUploadOrder() async {
    try{

      //1.由于已在添加订单任务时,已重置业务状态为false,则查出不存在业务异常的单号即可删除
      List<BeanUploadOrderDetail> recordOrderList=uploadOrderDetailBox!.getAll();
      recordOrderList.removeWhere((BeanUploadOrderDetail order){
        if (order.businessSuccess){
          //不存在业务异常的单号,可以删除
          uploadOrderDetailBox!.remove(order.id);
          //日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(order.fastOrderNo),'检查(本地)已追平删除本地订单!');
          return true;
        }else{
          return false;
        }
      });

      //2.剩余业务异常的订单调用api检测是否已追平
      XLogUtils.printLog('---检测本地订单是否已追平,存在业务异常订单:${recordOrderList.length}');
      if (recordOrderList.isEmpty){
        //所有订单已追平
        return;
      }
      List<String> fastOrderNos=[];
      for (BeanUploadOrderDetail order in recordOrderList){
        fastOrderNos.add(order.fastOrderNo!);
      }
      if (fastOrderNos.isEmpty){
        return;
      }

      Response_check_order? response= await RBBaseApi.checkOrderBusinessStatus(
          fastOrderNos: fastOrderNos
      );

      store?.runInTransaction(TxMode.write, (){

        if (response!=null){
          List<BeanCheckOrderData>? data=response.data;
          if (data!=null){
            for (BeanCheckOrderData iitem in data){
              if (iitem.businessSuccess){
                //api业务实际已追平,删除订单
                for(BeanUploadOrderDetail order in recordOrderList){
                  if (iitem.fastOrderNo==order.fastOrderNo){
                    uploadOrderDetailBox!.remove(order.id);
                    //日志
                    XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(order.fastOrderNo),'检查(api)已追平删除本地订单!');
                    recordOrderList.remove(order);
                    break;
                  }
                }
              }else{
                //更新错误信息
                for(BeanUploadOrderDetail order in recordOrderList){
                  if (iitem.fastOrderNo==order.fastOrderNo){
                    order.orderMsg=iitem.businessErrorMsg;
                    uploadOrderDetailBox!.put(order);
                    break;
                  }
                }
              }
            }
          }
        }
        XLogUtils.printLog('---检测本地订单是否已追平处理完毕,剩余未追平单: ${recordOrderList.length}, ${uploadOrderDetailBox!.count()}');
      });

    }catch (e){
      XLogUtils.printLog('---checkAndDeleteUploadOrder报错:$e');
    }
  }


  //查找本地订单(未追平的订单)ok 订单上传2.0
  static Map<String,dynamic> _findUploadOrderList2(BeanH5RequestPageLocalOrder request){

    BeanUploadOrderH5Response3 response =BeanUploadOrderH5Response3();

    try{

      int pageIndex=request.pageIndex;
      int pageSize=request.pageSize;
      //String? keyword=request.sword;

      if (pageIndex<=0||pageSize<=0){
        response.code="-1";
        return response.toJson();
      }
      //总商品数
      int totalCount=uploadOrderDetailBox!.count();
      XLogUtils.printLog('---UploadOrderList all size=$totalCount');

      //总页数
      int pageCount=0;
      if (totalCount/pageSize==0){
        pageCount=1;
      }else{
        pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
      }
      //偏离数=当前页数(第一页从1开始)*每页数量
      int offset=(pageIndex-1)*pageSize;


      List<BeanUploadOrderDetail> list=[];

      Query<BeanUploadOrderDetail> query=uploadOrderDetailBox!.query()
          .order(BeanUploadOrderDetail_.id,flags: Order.descending)
          .build();
      query.limit=pageSize;
      query.offset=offset;
      list = query.find();
      query.close();

      //
      List<dynamic> pushJsonList=[];
      for (BeanUploadOrderDetail sItem in list){
        XLogUtils.printLog('---查找未上传订单sItem.pushJson=${sItem.pushJson}');
        Map<String,dynamic> m=XJsonUtils.json2Map(sItem.pushJson);
        m['orderMsg']=sItem.orderMsg;
        pushJsonList.add(m);
      }

      response.code="200";
      response.PageIndex=pageIndex;
      response.PageCount=pageCount;
      response.totalCount=totalCount;
      response.items=pushJsonList;

      XLogUtils.printLog('---未追平订单h5JsonList=${list.length}');
      XLogUtils.printLog('----未追平订单h5JsonList:${XJsonUtils.obj2Json(response)}');

    }catch ( e){
      XLogUtils.printLog('---findUploadOrderList报错:$e');
    }

    return response.toJson();

  }


  //删除今天以前的购物车信息
  static void removeOldOrderShoppingcart(){
    try{

      store?.runInTransaction(TxMode.write, (){
        XLogUtils.printLog('---自动清除今天以前所有订单购物车!');
        //今天0点时间
        int longtime=XDateUtils.getToday0HourTime_ms();

        Query<BeanUploadOrderShoppingCart> query=uploadOrderShoppingCartBox!.query(BeanUploadOrderShoppingCart_.createDateLong.lessThan(longtime))
            .build();
        List<BeanUploadOrderShoppingCart> list=query.find();
        query.close();
        if(list.isNotEmpty){
          //删除
          List<int> ids=[];
          for(BeanUploadOrderShoppingCart shoppingCart in list){
            ids.add(shoppingCart.id);
          }
          uploadOrderShoppingCartBox!.removeMany(ids);
        }
      });

    }catch (e){
      XLogUtils.printLog('---removeOldOrderShoppingcart报错: $e');
    }

  }

  //登录成功重新检测和处理未上传订单2.0
  static void loginInitCheckUnUploadOrderTaskX(){

    try{
      //恢复
      uploadFailedTaskList.clear();
      //
      store?.runInTransaction(TxMode.write, (){
        //清除已上传订单
        Query<BeanUploadOrderTask> query_BeanUploadOrderTask_ok=uploadOrderTaskBox!.query(
            BeanUploadOrderTask_.synSuccess.equals(true)).build();
        List<BeanUploadOrderTask> list_BeanUploadOrderTask_ok=query_BeanUploadOrderTask_ok.find();
        query_BeanUploadOrderTask_ok.close();
        if(list_BeanUploadOrderTask_ok.isNotEmpty){
          List<int> ids=[];
          for(BeanUploadOrderTask iOk in list_BeanUploadOrderTask_ok){
            ids.add(iOk.id);
          }
          uploadOrderTaskBox!.removeMany(ids);
        }

        //重新处理未上传订单
        Query<BeanUploadOrderTask> query_BeanUploadOrderTask=uploadOrderTaskBox!.query(
            BeanUploadOrderTask_.synSuccess.equals(false)).build();
        List<BeanUploadOrderTask> list_UploadOrderTask_db=query_BeanUploadOrderTask.find();
        query_BeanUploadOrderTask.close();

        //未清除的上传任务全部添加到内存队列
        for(BeanUploadOrderTask uploadOrderTask1 in list_UploadOrderTask_db){
          if(!uploadFailedTaskList.contains(uploadOrderTask1)){
            uploadOrderTask1.isFailedTaskUpLoading=false;
            uploadOrderTask1.failedTaskUploadCount=0;
            uploadFailedTaskList.add(uploadOrderTask1);
          }
        }

      });
    }catch(e){
      XLogUtils.printLog('---loginInitCheckUnUploadOrderTaskX报错: $e');
    }finally{
      Future((){
        //重试失败任务
        reTryFailUploadTask();
      });
    }

  }

  //重试失败任务
  static void reTryFailUploadTask(){
    XLogUtils.printLog('---重试失败上传任务,uploadFailedTaskList= ${uploadFailedTaskList.length}');
    if(uploadFailedTaskList.isNotEmpty){
      for(BeanUploadOrderTask u in uploadFailedTaskList){
        if(!u.isFailedTaskUpLoading && u.failedTaskUploadCount<3){
          u.isFailedTaskUpLoading=true;
          _uploadOrderTaskX(u);
          break;
        }
      }
    }

  }

  //上传订单处理
  static List<BeanUploadOrderTask> uploadFailedTaskList=[];//内存失败任务队列
  static void _uploadOrderTaskX(BeanUploadOrderTask waitUploadItem) async{

    //上传任务
    Response_upload_order? response = await RBBaseApi.uploadOrderTask2(
        request: XJsonUtils.json2Map(waitUploadItem.pushJson)
    );
    //日志
    XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(waitUploadItem.fastOrderNo),'订单上传2.0结果: ${XJsonUtils.obj2Json(response)}, 上传参数=${waitUploadItem.pushJson}');
    String? fastOrderNo = waitUploadItem.fastOrderNo;

    try{

      if (response != null && '200'==response.code) {
        //成功,删除任务队列
        XLogUtils.printLog('---同步上传2.0成功');

        //失败记录
        uploadFailedTaskList.removeWhere((item1){
          if(item1.fastOrderNo==fastOrderNo){
            return true;
          }
          return false;
        });

        //db
        store?.runInTransaction(TxMode.write, (){
          //
          Query<BeanUploadOrderTask> query_BeanUploadOrderTask=uploadOrderTaskBox!.query(
              BeanUploadOrderTask_.fastOrderNo.equals(fastOrderNo??'')
          ).build();
          List<BeanUploadOrderTask> list_BeanUploadOrderTask=query_BeanUploadOrderTask.find();
          query_BeanUploadOrderTask.close();
          XLogUtils.printLog('---同步上传2.0成功,上传任务uploadOrderTaskBox=${list_BeanUploadOrderTask.length}');

          //删除任务队列(标识)
          if(list_BeanUploadOrderTask.isNotEmpty){
            for(BeanUploadOrderTask uploadOrderTask1 in list_BeanUploadOrderTask){
              uploadOrderTask1.synSuccess=true;
            }
            uploadOrderTaskBox!.putMany(list_BeanUploadOrderTask);
          }

          //查找订单,更新追平状态
          Query<BeanUploadOrderDetail> query_BeanUploadOrderDetail = uploadOrderDetailBox!.query(
              BeanUploadOrderDetail_.fastOrderNo.equals(waitUploadItem.fastOrderNo!)
          ).build();
          List<BeanUploadOrderDetail> list_BeanUploadOrderDetail = query_BeanUploadOrderDetail.find();
          query_BeanUploadOrderDetail.close();
          XLogUtils.printLog('---查找订单,list_BeanUploadOrderDetail=${list_BeanUploadOrderDetail.length}');

          //防止重复单号情况
          if(list_BeanUploadOrderDetail.isNotEmpty){
            for (BeanUploadOrderDetail orderItem in list_BeanUploadOrderDetail) {
              orderItem.synSuccess = true;
              orderItem.businessSuccess = false;
            }
            uploadOrderDetailBox!.putMany(list_BeanUploadOrderDetail);
          }

          XLogUtils.printLog('---上传任务2.0成功,删除任务(db)');
          //日志
          XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(waitUploadItem.fastOrderNo),'上传任务2.0成功,删除任务(db)');

        });


      }else{
        //失败
        XLogUtils.printLog('---同步上传2.0失败');
        waitUploadItem.isFailedTaskUpLoading=false;
        waitUploadItem.failedTaskUploadCount+=1;

        //添加到内存失败任务队列
        if(!uploadFailedTaskList.contains(waitUploadItem)){
          uploadFailedTaskList.add(waitUploadItem);
        }else{
          for(BeanUploadOrderTask u in uploadFailedTaskList){
            if(waitUploadItem==u){
              u.isFailedTaskUpLoading=false;
              break;
            }
          }
        }

      }

    }catch (e,tr){
      XLogUtils.printLog('---_uploadOrderTaskX上传任务2.0抛出错误: $e, $tr');
      //日志
      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(waitUploadItem.fastOrderNo),'上传任务2.0抛出错误: $e');
    }finally{
      Future((){
        reTryFailUploadTask();
      });
    }

  }


  //极速版1.0////////////////////////////////////////////////////
  //保存离线订单
  static void saveOfflineOrder(BeanOfflineDBOrder item){
    orderBox!.putAsync(item);
  }
  static void delOfflineOrder(int id){
    orderBox!.removeAsync(id);
  }
  static void savePendingOrder(BeanOfflineDBPendingOrder item){
    pendingOrderBox!.putAsync(item);
  }
  static void delPendingOrder(int id){
    pendingOrderBox!.removeAsync(id);
  }
  static void delAllPendingOrder(){
    pendingOrderBox!.removeAllAsync();
  }
  static int getPendingOrderTotalCount(){
    return pendingOrderBox!.count();
  }

  //获得挂单列表(旧)
  static void getOfflinePendingOrderList(int pageIndex,int pageSize,XFunctionObjectBoxCallback callback){

    Future((){
      BeanUploadOrderH5Response3 response =BeanUploadOrderH5Response3();

      try{

        if (pageIndex<=0||pageSize<=0){
          response.code="-1";
          callback(response.toJson());
        }
        //

        response.code='200';

        //总商品数
        int totalCount=pendingOrderBox!.count();

        //总页数
        int pageCount=0;
        if (totalCount/pageSize==0){
          pageCount=1;
        }else{
          pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
        }
        //偏离数=当前页数(第一页从1开始)*每页数量
        int offset=(pageIndex-1)*pageSize;

        List<BeanOfflineDBPendingOrder> list=[];

        Query<BeanOfflineDBPendingOrder> query=pendingOrderBox!.query()
            .order(BeanOfflineDBPendingOrder_.id,flags: Order.descending)
            .build();
        query.limit=pageSize;
        query.offset=offset;
        list = query.find();
        query.close();

        //
        List<dynamic> pushJsonList=[];
        for (BeanOfflineDBPendingOrder sItem in list){
          Map<String,dynamic> mapItem=XJsonUtils.json2Map(sItem.json);

          Map<String, dynamic> m={};
          m['longId']=sItem.id;
          m['serialNumber']=sItem.serialNumber;
          m['creatDate']=sItem.creatDate;
          m['totalMoney']=sItem.totalMoney;
          m['json']=mapItem;

          pushJsonList.add(m);
        }

        response.code="200";
        response.PageIndex=pageIndex;
        response.PageCount=pageCount;
        response.totalCount=totalCount;
        response.items=pushJsonList;

        XLogUtils.printLog('---挂单列表,size=${list.length}');

        callback(response.toJson());

      }catch ( e){
        XLogUtils.printLog('---getOfflinePendingOrderList报错:$e');
        callback(response.toJson());
      }

    });

  }
  //获得挂单列表(新)
  static void getPendingOrderListWithItems(int pageIndex,int pageSize,XFunctionObjectBoxCallback callback){

    Future((){
      BeanUploadOrderH5Response3 response =BeanUploadOrderH5Response3();

      try{

        if (pageIndex<=0||pageSize<=0){
          response.code="-1";
          callback(response.toJson());
        }
        //

        response.code='200';

        //总商品数
        int totalCount=pendingOrderBox!.count();

        //总页数
        int pageCount=0;
        if (totalCount/pageSize==0){
          pageCount=1;
        }else{
          pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
        }
        //偏离数=当前页数(第一页从1开始)*每页数量
        int offset=(pageIndex-1)*pageSize;

        List<BeanOfflineDBPendingOrder> list=[];

        Query<BeanOfflineDBPendingOrder> query=pendingOrderBox!.query()
            .order(BeanOfflineDBPendingOrder_.id,flags: Order.descending)
            .build();
        query.limit=pageSize;
        query.offset=offset;
        list = query.find();
        query.close();

        //
        List<dynamic> pushJsonList=[];
        for (BeanOfflineDBPendingOrder sItem in list){
          dynamic mapItem;
          if(!XStringUtils.isEmpty(sItem.items)){
            if(sItem.items!.startsWith('[')){
              mapItem=XJsonUtils.json2List(sItem.items);
            }else{
              mapItem=XJsonUtils.json2Map(sItem.items);
            }
          }

          Map<String, dynamic> m={};
          m['longId']=sItem.id;
          m['serialNumber']=sItem.serialNumber;
          m['creatDate']=sItem.creatDate;
          m['totalMoney']=sItem.totalMoney;
          m['json']=mapItem;

          pushJsonList.add(m);
        }

        response.code="200";
        response.PageIndex=pageIndex;
        response.PageCount=pageCount;
        response.totalCount=totalCount;
        response.items=pushJsonList;

        XLogUtils.printLog('---挂单列表,size=${list.length}');

        callback(response.toJson());

      }catch (e){
        XLogUtils.printLog('---getOfflinePendingOrderList报错:$e');
        callback(response.toJson());
      }

    });

  }
  //挂单详情
  static BeanUploadOrderH5Response5 getPendingOrderDetail(int longId){

    BeanUploadOrderH5Response5 response =BeanUploadOrderH5Response5();
    response.code="500";
    response.msg="没有找到对应的挂单详情";

    try{

      Query<BeanOfflineDBPendingOrder> query=pendingOrderBox!
          .query(BeanOfflineDBPendingOrder_.id.equals(longId))
          .build();
      List<BeanOfflineDBPendingOrder> list = query.find();
      query.close();

      if(list.isNotEmpty){
        response.code='200';
        BeanOfflineDBPendingOrder sItem=list.first;

        Map<String,dynamic> mapItem=XJsonUtils.json2Map(sItem.json);

        Map<String, dynamic> m={};
        m['longId']=sItem.id;
        m['serialNumber']=sItem.serialNumber;
        m['creatDate']=sItem.creatDate;
        m['totalMoney']=sItem.totalMoney;
        m['json']=mapItem;

        response.code="200";
        response.msg="成功找到对应的挂单详情";
        response.items=m;

      }

    }catch ( e){
      XLogUtils.printLog('---getPendingOrderDetail报错:$e');
    }

    return response;

  }
  //获得下单收银订单列表ok
  static void getOfflineOrderList(
      int pageIndex,
      int pageSize,
      String? keyword,
      XFunctionObjectBoxCallback callback){

    Future((){
      BeanUploadOrderH5Response3 response =BeanUploadOrderH5Response3();

      try{

        if (pageIndex<=0||pageSize<=0){
          response.code="-1";
          callback(response.toJson());
        }
        //

        response.code='200';

        //总商品数
        int totalCount=orderBox!.count();

        //总页数
        int pageCount=0;
        if (totalCount/pageSize==0){
          pageCount=1;
        }else{
          pageCount=(totalCount%pageSize==0)?(totalCount/pageSize).truncate():((totalCount/pageSize).truncate()+1);
        }
        //偏离数=当前页数(第一页从1开始)*每页数量
        int offset=(pageIndex-1)*pageSize;

        List<BeanOfflineDBOrder> list=[];

        if (XStringUtils.isEmpty(keyword)){
          //全部
          Query<BeanOfflineDBOrder> query=orderBox!.query()
              .order(BeanOfflineDBOrder_.id,flags: Order.descending)
              .build();
          query.limit=pageSize;
          query.offset=offset;
          list = query.find();
          query.close();
        }else{
          //按keyword
          Query<BeanOfflineDBOrder> query=orderBox!.query(BeanOfflineDBOrder_.orderNo.equals(keyword!))
              .order(BeanOfflineDBOrder_.id,flags: Order.descending)
              .build();
          query.limit=pageSize;
          query.offset=offset;
          list = query.find();
          query.close();
        }

        //
        List<dynamic> pushJsonList=[];
        for (BeanOfflineDBOrder sItem in list){
          Map<String,dynamic> mapItem=XJsonUtils.json2Map(sItem.json);

          Map<String, dynamic> m={};
          m['longId']=sItem.id;
          m['orderId']=sItem.orderId;
          m['orderNo']=sItem.orderNo;
          m['orderDate']=sItem.orderDate;
          m['json']=mapItem;

          pushJsonList.add(m);
        }

        response.code="200";
        response.PageIndex=pageIndex;
        response.PageCount=pageCount;
        response.totalCount=totalCount;
        response.items=pushJsonList;

        XLogUtils.printLog('---订单列表,size=${list.length}');

        callback(response.toJson());

      }catch (e){
        XLogUtils.printLog('---getOfflinePendingOrderList报错:$e');
        callback(response.toJson());
      }

    });



  }

//本地促销/////////////////////////////////////////////
  /*
    购物车单品促销:
    第一步:购物车所有商品促销planIds, 按商品,分类,系列,品牌 getShoppingCartItemsPromotionPlanIds(json)
    第二步:获得单品促销plan对应的促销json: getShoppingCartItemsPromotionJsons(json)
    第三步: 获得单品秒杀促销: getShoppingCartItemTimedPromotions(json)
    第四步: 获得购物商品促销清单(一般是赠品、换购、凑单入口) 返回分页的促销品信息  getShoppingCartItemListPromotions({"pageIndex":1,"pageSize":20,"planId":"sdfsdfsfsdfsasg"}),
    订单整单促销:
    第一步:获得订单整单所有促销: getOrderPromotions();
    第二步:根据整单促销planId和购物车商品,是否排除匹配,返回符合条件的specId: getOrderItemsPromotionSpecIds(json)

     */

  //获得购物车商品拥有的促销(按商品,分类,品牌,系列,...)
  static void getShoppingCartItemsPromotionPlanIds(
      RequestShoppingCartItemPromotionPlanIds request,
      XFunctionObjectBoxCallback callback
      ){

    Future((){
      ResponseShoppingCartItemPlanIds response5=ResponseShoppingCartItemPlanIds();
      response5.code="-1";

      try{

        List<BeanShoppingCartRequestPromotionItems>? items=request.items;

        if (items==null || items.isEmpty){
          response5.msg="购物车商品为空";
          //h5协商为空则不返回
          //callback.callback(XJsonUtils.obj2String(response5));
          return;
        }

        response5.code="200";
        response5.msg="成功";

        //商品促销返回结果
        List<BeanShoppingCartItemPromotionPlanIds> listPlanidsApply=[];
        List<BeanShoppingCartItemPromotionPlanIds> listPlanidsExcl=[];

        //商品促销

        //应用
        for(BeanShoppingCartRequestPromotionItems goodItem in items){
          String specId=goodItem.specId??'';
          BeanShoppingCartItemPromotionPlanIds beanShoppingCartItemPromotionPlanIds=BeanShoppingCartItemPromotionPlanIds();
          beanShoppingCartItemPromotionPlanIds.specId=specId;
          beanShoppingCartItemPromotionPlanIds.excl=false;

          Set<String> planIds={};

          //L.sdk("---specId="+specId);

          //1.查找商品拥有的促销
          if(!XStringUtils.isEmpty(specId)){

            Query<DbCXProduct> queryProduct =box_DbCXProduct!.query(
                DbCXProduct_.productType.equals('-1')
                    .and(DbCXProduct_.typeId.equals(specId)
                    .and(DbCXProduct_.excl.equals(false)
                ))).build();

            List<DbCXProduct> listProduct=queryProduct.find();
            XLogUtils.printLog("---商品拥有的促销=${XJsonUtils.obj2Json(listProduct)}, size=${listProduct.length}");
            for (DbCXProduct product in listProduct){
              planIds.add(product.planIdEach??'');
            }
          }

          //2.查找品牌拥有的促销
          String brandId=goodItem.brandId??'';
          if(!XStringUtils.isEmpty(brandId)){

            Query<DbCXProduct> queryBrand =box_DbCXProduct!.query(
                DbCXProduct_.productType.equals('1')
                    .and(DbCXProduct_.typeId.equals(brandId)
                    .and(DbCXProduct_.excl.equals(false)
                ))).build();


            List<DbCXProduct> listBrand=queryBrand.find();
            XLogUtils.printLog("---品牌拥有的促销=${XJsonUtils.obj2Json(listBrand)}, size=${listBrand.length}");
            for (DbCXProduct product in listBrand){
              planIds.add(product.planIdEach??'');
            }
            //
          }

          //3.查找系列拥有的促销
          String seriesId=goodItem.seriesId??'';
          if (!XStringUtils.isEmpty(seriesId)){

            Query<DbCXProduct> querySeries =box_DbCXProduct!.query(
                DbCXProduct_.productType.equals('2')
                    .and(DbCXProduct_.typeId.equals(seriesId)
                    .and(DbCXProduct_.excl.equals(false)
                ))).build();

            List<DbCXProduct> listSeries=querySeries.find();
            XLogUtils.printLog("---系列拥有的促销=${XJsonUtils.obj2Json(listSeries)}, size=${listSeries.length}");
            for (DbCXProduct product in listSeries){
              planIds.add(product.planIdEach??'');
            }
          }

          //4.查找分类拥有的促销
          List<String> llItemtypeids=goodItem.itemTypeIds??[];
          if(llItemtypeids.isNotEmpty){

            Query<DbCXProduct> queryItemtypeids =box_DbCXProduct!.query(
                DbCXProduct_.productType.equals('0')
                    .and(DbCXProduct_.typeId.oneOf(llItemtypeids)
                    .and(DbCXProduct_.excl.equals(false)
                ))).build();

            List<DbCXProduct> listItemtypeids=queryItemtypeids.find();
            XLogUtils.printLog("---分类拥有的促销=${XJsonUtils.obj2Json(listItemtypeids)}, size=${listItemtypeids.length}");

            for (DbCXProduct product in listItemtypeids){
              planIds.add(product.planIdEach??'');
            }
            //
          }

          //5.套餐促销
          if(!XStringUtils.isEmpty(specId)){
            //1、先根据规格id 查itemBomProducts 得到bomIds (得到商品所在的促销品清单id列表)

            Query<DbCXItemBomProduct> queryItembomproduct =box_DbCXItemBomProduct!.query(
                DbCXItemBomProduct_.specId.equals(specId)).build();

            List<DbCXItemBomProduct> listItembomproduct=queryItembomproduct.find();
            XLogUtils.printLog("---商品拥有的bomIds=${XJsonUtils.obj2Json(listItembomproduct)}, size=${listItembomproduct.length}");
            List<String> bomIdSet=[];
            for (DbCXItemBomProduct itemBomProduct in listItembomproduct){
              bomIdSet.add(itemBomProduct.bomId??'');
            }

            //2、根据bomId 查询suitBoms 得到组合套餐促销id
            if (bomIdSet.isNotEmpty){

              Query<DbCXSuitBom> querySuitbom =box_DbCXSuitBom!.query(
                  DbCXSuitBom_.bomId.oneOf(bomIdSet)).build();

              List<DbCXSuitBom> listSuitbom=querySuitbom.find();

              //
              for (DbCXSuitBom suitBom in listSuitbom){
                planIds.add(suitBom.planId??'');
              }
              XLogUtils.printLog("---套餐拥有的促销=${XJsonUtils.obj2Json(listSuitbom)}, size=${listSuitbom.length}");
            }

          }

          beanShoppingCartItemPromotionPlanIds.planIds=[];
          beanShoppingCartItemPromotionPlanIds.planIds!.addAll(planIds);
          if(beanShoppingCartItemPromotionPlanIds.planIds!.isNotEmpty){
            //
            listPlanidsApply.add(beanShoppingCartItemPromotionPlanIds);
          }


        }

        //排除
        for(BeanShoppingCartRequestPromotionItems goodItem in items){
          String specId=goodItem.specId??'';
          BeanShoppingCartItemPromotionPlanIds beanShoppingCartItemPromotionPlanIds= BeanShoppingCartItemPromotionPlanIds();
          beanShoppingCartItemPromotionPlanIds.specId=specId;
          beanShoppingCartItemPromotionPlanIds.excl=true;

          Set<String> planIds={};

          //L.sdk("---specId="+specId);

          //1.查找商品拥有的促销
          if(!XStringUtils.isEmpty(specId)){

            Query<DbCXProduct> queryProduct =box_DbCXProduct!.query(
                DbCXProduct_.productType.equals('-1')
                    .and(DbCXProduct_.typeId.equals(specId)
                    .and(DbCXProduct_.excl.equals(true)
                ))).build();

            List<DbCXProduct> listProduct=queryProduct.find();
            XLogUtils.printLog("---商品拥有的促销=${XJsonUtils.obj2Json(listProduct)}, size=${listProduct.length}");
            for (DbCXProduct product in listProduct){
              planIds.add(product.planIdEach??'');
            }
          }

          //2.查找品牌拥有的促销
          String brandId=goodItem.brandId??'';
          if(!XStringUtils.isEmpty(brandId)){

            Query<DbCXProduct> queryBrand =box_DbCXProduct!.query(
                DbCXProduct_.productType.equals('1')
                    .and(DbCXProduct_.typeId.equals(brandId)
                    .and(DbCXProduct_.excl.equals(true)
                ))).build();

            List<DbCXProduct> listBrand=queryBrand.find();
            XLogUtils.printLog("---品牌拥有的促销=${XJsonUtils.obj2Json(listBrand)}, size=${listBrand.length}");
            for (DbCXProduct product in listBrand){
              planIds.add(product.planIdEach??"");
            }
            //
          }

          //3.查找系列拥有的促销
          String seriesId=goodItem.seriesId??'';
          if (!XStringUtils.isEmpty(seriesId)){

            Query<DbCXProduct> querySeries =box_DbCXProduct!.query(
                DbCXProduct_.productType.equals('2')
                    .and(DbCXProduct_.typeId.equals(seriesId)
                    .and(DbCXProduct_.excl.equals(true)
                ))).build();

            List<DbCXProduct> listSeries=querySeries.find();
            XLogUtils.printLog("---系列拥有的促销=${XJsonUtils.obj2Json(listSeries)}, size=${listSeries.length}");
            for (DbCXProduct product in listSeries){
              planIds.add(product.planIdEach??'');
            }
          }

          //4.查找分类拥有的促销
          List<String> llItemtypeids=goodItem.itemTypeIds??[];
          if(llItemtypeids.isNotEmpty){

            Query<DbCXProduct> queryItemtypeids =box_DbCXProduct!.query(
                DbCXProduct_.productType.equals('0')
                    .and(DbCXProduct_.typeId.oneOf(llItemtypeids)
                    .and(DbCXProduct_.excl.equals(true)
                ))).build();

            List<DbCXProduct> listItemtypeids=queryItemtypeids.find();
            XLogUtils.printLog("---分类拥有的促销=${XJsonUtils.obj2Json(listItemtypeids)}, size=${listItemtypeids.length}");

            for (DbCXProduct product in listItemtypeids){
              planIds.add(product.planIdEach??'');
            }
            //
          }


          beanShoppingCartItemPromotionPlanIds.planIds=[];
          beanShoppingCartItemPromotionPlanIds.planIds!.addAll(planIds);
          //
          if(beanShoppingCartItemPromotionPlanIds.planIds!.isNotEmpty){
            listPlanidsExcl.add(beanShoppingCartItemPromotionPlanIds);
          }

        }

        //h5协商为空则不返回
        response5.planIds =listPlanidsApply;
        response5.planIds_excl=listPlanidsExcl;
        callback(response5.toJson());

      }catch (e){
        XLogUtils.printLog('---getShoppingCartItemsPromotionPlanIds报错:$e');
        //h5协商为空则不返回
        callback(response5.toJson());
      }
    });
  }

  //获得促销PlanIds对应的促销json
  static void getShoppingCartItemsPromotionJsons(
      List<String> planIds,
      XFunctionObjectBoxCallback callback
      ){

    Future((){

      ResponseShoppingCartItemPromotionJson responseShoppingCartItemPromotionJson= ResponseShoppingCartItemPromotionJson();

      try{
        responseShoppingCartItemPromotionJson.code="200";
        responseShoppingCartItemPromotionJson.msg="成功";


        //促销规则json

        Query<DbCXPromotion> queryPromotion =box_DbCXPromotion!.query(
            DbCXPromotion_.planId.notEquals('')
                .and(DbCXPromotion_.planId.oneOf(planIds)
            )).build();

        List<DbCXPromotion> listPromotion=queryPromotion.find();
        //
        List<BeanShoppingCartItemPromotionJson> listBeanshoppingcartitempromotionjson=[];
        for(DbCXPromotion iitem in listPromotion){
          //按时间过滤
          bool isInTime=true;
          String beginDate=iitem.beginDate??'';
          String endDate=iitem.endDate??'';
          if(!XStringUtils.isEmpty(beginDate) && !XStringUtils.isEmpty(endDate)){
            //init
            isInTime=false;
            try{
              int startTime=int.tryParse(beginDate)??0;
              int endTime=int.tryParse(endDate)??0;
              int now=XDateUtils.getCurrentTime_ms();
              if(now>=startTime && now<=endTime){
                isInTime=true;
              }
            }catch (e){
              XLogUtils.printLog('---解析startTime/endTime报错:$e');
            }
          }

          if(isInTime){
            //在有效时间内
            BeanShoppingCartItemPromotionJson itemPromotionJson= BeanShoppingCartItemPromotionJson();
            itemPromotionJson.projectId=iitem.projectId;
            itemPromotionJson.version=iitem.version;
            itemPromotionJson.planId=iitem.planId;
            itemPromotionJson.planType=iitem.planType;
            itemPromotionJson.promotion=XJsonUtils.json2Map(iitem.promotionJson);
            listBeanshoppingcartitempromotionjson.add(itemPromotionJson);
          }
        }
        /*
                    适配: 1.先插入增量后插入全量情况; 2.补低版本增量情况
                    避免增量删除了某些规则情况: 同一projectId,只取版本号高的
                     */
        //1.算出每个projectId的最高版本
        Map<String,int> projectidVersion={};
        for(BeanShoppingCartItemPromotionJson iitem in listBeanshoppingcartitempromotionjson){
          int? noteVersion=projectidVersion['${iitem.projectId}'];
          if(noteVersion==null){
            projectidVersion['${iitem.projectId}']=iitem.version;
          }else{
            if(noteVersion<iitem.version){
              projectidVersion['${iitem.projectId}']=iitem.version;
            }
          }
        }
        //2.清除每个projectId的低版本促销
        listBeanshoppingcartitempromotionjson.removeWhere((BeanShoppingCartItemPromotionJson element){
          int lastVersion=projectidVersion['${element.projectId}']??0;
          if(element.version<lastVersion){
            return true;
          }
          return false;
        });


        //3.去重
        Set<BeanShoppingCartItemPromotionJson> setPromotionjson={};
        setPromotionjson.addAll(listBeanshoppingcartitempromotionjson);
        //
        responseShoppingCartItemPromotionJson.promotions=[];
        responseShoppingCartItemPromotionJson.promotions!.addAll(setPromotionjson);
        callback(responseShoppingCartItemPromotionJson.toJson());

      }catch (e){
        XLogUtils.printLog('---getShoppingCartItemsPromotionJsons报错:$e');
        responseShoppingCartItemPromotionJson.code="-1";
        responseShoppingCartItemPromotionJson.msg="失败";
        callback(responseShoppingCartItemPromotionJson.toJson());
      }

    });
  }
  //获得购物车商品对应的秒杀促销
  static void getShoppingCartItemTimedPromotions(
      RequestShoppingCartItemTimedPromotion request,
      XFunctionObjectBoxCallback callback
      ){

    Future((){

      ResponseShoppingCartItemTimeds response6= ResponseShoppingCartItemTimeds();
      response6.code="-1";

      try{
        if (XStringUtils.isEmpty(request.planId)
        ){
          response6.msg="planId不能为空";
          callback(response6.toJson());
          return;
        }

        response6.code="200";
        response6.msg="成功";
        response6.planId=request.planId;

        //秒杀规则
        Query<DbCXItemTimed> queryItemtimed =box_DbCXItemTimed!.query(
            DbCXItemTimed_.planId.equals(request.planId!))
            .order(DbCXItemTimed_.version,flags: Order.descending)
            .build();

        List<DbCXItemTimed> listItemtimed=queryItemtimed.find();

        //排序去重
        Set<DbCXItemTimed> setDbcxitemtimed={};
        setDbcxitemtimed.addAll(listItemtimed);

        XLogUtils.printLog("---商品的秒杀促销=${XJsonUtils.obj2Json(setDbcxitemtimed)}, size=${setDbcxitemtimed.length}");
        response6.itemTimeds=[];
        response6.itemTimeds!.addAll(setDbcxitemtimed);
        //
        callback(response6.toJson());

      }catch (e){
        XLogUtils.printLog('---getShoppingCartItemTimedPromotions报错:$e');
        callback(response6.toJson());
      }

    });
  }
  //获得订单互斥促销
  static void getMutexPlans(
      RequestOrderMutexPlans request,
      XFunctionObjectBoxCallback callback
      ){

    Future((){

      ResponsOrderMutexPlans response6= ResponsOrderMutexPlans();
      response6.code="-1";

      try{
        if (XStringUtils.isEmpty(request.planId)
        ){
          response6.msg="planId不能为空";
          callback(response6.toJson());
          return;
        }

        response6.code="200";
        response6.msg="成功";
        response6.planId=request.planId;

        //
        Query<DbCXMutexPlan> queryDbcxmutexplan =box_DbCXMutexPlan!.query(
            DbCXMutexPlan_.planId.equals(request.planId!))
            .order(DbCXMutexPlan_.version,flags: Order.descending)
            .build();

        List<DbCXMutexPlan> listDbcxmutexplan=queryDbcxmutexplan.find();

        //排序去重
        Set<DbCXMutexPlan> setDbcxmutexplan={};
        setDbcxmutexplan.addAll(listDbcxmutexplan);

        List<String> mutexPlanIds=[];
        for(DbCXMutexPlan iitem in setDbcxmutexplan){
          if (!mutexPlanIds.contains(iitem.mutexPlanId)){
            mutexPlanIds.add(iitem.mutexPlanId??'');
          }
        }
        XLogUtils.printLog("---商品互斥=${XJsonUtils.obj2Json(mutexPlanIds)}, size=${mutexPlanIds.length}");
        response6.mutexPlanIds=mutexPlanIds;
        //
        callback(response6.toJson());

      }catch (e){
        XLogUtils.printLog('---getMutexPlans报错:$e');
        callback(response6.toJson());
      }

    });
  }
  //获得购物车商品促销清单
  static void getShoppingCartItemListPromotions(
      RequestShoppingCartItemListPromotion request,
      XFunctionObjectBoxCallback callback
      ){

    Future((){

      ResponseShoppingCartItemList response= ResponseShoppingCartItemList();
      response.code="-1";
      response.bomId=request.bomId;

      try{
        if (request.pageIndex==0
            ||request.pageSize==0
            || XStringUtils.isEmpty(request.bomId)
        ){
          response.msg="传参错误";
          callback(response.toJson());
          return;
        }

        response.code="200";
        response.msg="成功";
        List<dynamic> specItemList=[];

        //总页数
        int pageCount=0;
        //总商品数
        int totalCount=0;


        //商品促销清单

        Query<DbCXItemBomProduct> queryItembomproduct =box_DbCXItemBomProduct!
            .query(DbCXItemBomProduct_.bomId.equals(request.bomId!))
            .build();

        //计算分页,总商品数
        totalCount=queryItembomproduct.count();
        if (totalCount/request.pageSize==0){
          pageCount=1;
        }else{
          pageCount=(totalCount%request.pageSize==0)?(totalCount/request.pageSize).truncate():((totalCount/request.pageSize).truncate()+1);
        }
        //偏离数=当前页数(第一页从1开始)*每页数量
        int offset=(request.pageIndex-1)*request.pageSize;

        queryItembomproduct.limit=request.pageSize;
        queryItembomproduct.offset=offset;
        List<DbCXItemBomProduct> listItembomproduct = queryItembomproduct.find();
        queryItembomproduct.close();

        XLogUtils.printLog("---商品促销清单=${XJsonUtils.obj2Json(listItembomproduct)}");

        response.PageIndex=request.pageIndex;
        response.PageCount=pageCount;
        response.totalCount=totalCount;

        for(DbCXItemBomProduct iitem in listItembomproduct){
          //查找规格商品
          Query<BeanOfflineDBGoodSpec> querySpec=goodSpecBox!
              .query(
              BeanOfflineDBGoodSpec_.isDel.equals(false)
                  .and(BeanOfflineDBGoodSpec_.specId.equals(iitem.specId??'')))
              .build();

          List<BeanOfflineDBGoodSpec> listSpec=querySpec.find();
          if(listSpec.isNotEmpty){
            XLogUtils.printLog("---specId存在商品=${iitem.specId}");
            BeanOfflineDBGoodSpec spec=listSpec.first;
            dynamic specItem = XJsonUtils.json2Map(spec.json);
            specItem['giftMustQty']=iitem.giftMustQty;
            specItem['giftMustSel']=iitem.giftMustSel;
            specItemList.add(specItem);
          }
        }

        response.items=specItemList;
        XLogUtils.printLog("---specItemList=${specItemList.length}");

        //
        callback(response.toJson());

      }catch (e){
        XLogUtils.printLog('---getShoppingCartItemListPromotions报错:$e');
        callback(response.toJson());
      }

    });
  }
  //获得整单指定商品(按商品,品牌,系列,分类)条件,是否排除,整单planId, 返回符合条件的商品规格id
  static void getOrderItemsPromotionSpecIds(
      RequestOrderItemPromotion request,
      XFunctionObjectBoxCallback callback
      ){

    Future((){

      ResponseOrderItemPromotionSpecIds response= ResponseOrderItemPromotionSpecIds();
      response.code="-1";

      try{

        if(request.planIds==null || request.planIds!.isEmpty){
          response.msg="planIds为空";
          callback(response.toJson());
          return;
        }

        Set<String> planIds={};
        planIds.addAll(request.planIds!);
        RequestShoppingCartItemPromotionPlanIds? requestShoppingCartItemPromotionPlanIds=request.shoppingCartItems;

        if(requestShoppingCartItemPromotionPlanIds==null
            || requestShoppingCartItemPromotionPlanIds.items==null
            ||requestShoppingCartItemPromotionPlanIds.items!.isEmpty){
          response.msg="购物车商品为空";
          callback(response.toJson());
          return;
        }

        List<BeanShoppingCartRequestPromotionItems> items=requestShoppingCartItemPromotionPlanIds.items!;

        List<BeanOrderItemPromotionSpecIds> specidsProductApply=[];//商品应用
        List<BeanOrderItemPromotionSpecIds> specidsProductExcl=[];//商品排除
        List<BeanOrderItemPromotionSpecIds> specidsGroupApply=[];//分类品牌系列应用
        List<BeanOrderItemPromotionSpecIds> specidsGroupExcl=[];//分类品牌系列排除

        response.code="200";
        response.msg="成功";

        //按商品 应用
        for(String sPlanId in planIds){
          BeanOrderItemPromotionSpecIds sItem= BeanOrderItemPromotionSpecIds();
          sItem.planId=sPlanId;
          sItem.excl=false;
          sItem.type=0;

          Set<String> specIds={};

          for(BeanShoppingCartRequestPromotionItems goodItem in items) {
            String specId = goodItem.specId??'';
            //查找商品拥有的促销
            if (!XStringUtils.isEmpty(specId)) {
              Query<DBCXOrderProduct> queryProduct = box_DBCXOrderProduct!.query(
                  DBCXOrderProduct_.productType.equals('-1').and(
                      DBCXOrderProduct_.typeId.equals(specId).and(
                          DBCXOrderProduct_.excl.equals(sItem.excl??false).and(
                              DBCXOrderProduct_.planId.equals(sItem.planId??'')
                          )
                      )
                  )
              ).build();
              List<DBCXOrderProduct> listProduct = queryProduct.find();
              XLogUtils.printLog("---整单促销,按商品 =${XJsonUtils.obj2Json(listProduct)}, size=${listProduct.length}");
              if (listProduct.isNotEmpty) {
                specIds.add(specId);
              }
            }
          }
          sItem.specIds=[];
          sItem.specIds!.addAll(specIds);
          if(sItem.specIds!.isNotEmpty){
            specidsProductApply.add(sItem);
          }
        }

        //按商品 排除
        for(String sPlanId in planIds){
          BeanOrderItemPromotionSpecIds sItem= BeanOrderItemPromotionSpecIds();
          sItem.planId=sPlanId;
          sItem.excl=true;
          sItem.type=0;

          Set<String> specIds={};

          for(BeanShoppingCartRequestPromotionItems goodItem in items) {
            String specId = goodItem.specId??'';
            //查找商品拥有的促销
            if (!XStringUtils.isEmpty(specId)) {

              Query<DBCXOrderProduct> queryProduct = box_DBCXOrderProduct!.query(
                  DBCXOrderProduct_.productType.equals('-1').and(
                      DBCXOrderProduct_.typeId.equals(specId).and(
                          DBCXOrderProduct_.excl.equals(sItem.excl??false).and(
                              DBCXOrderProduct_.planId.equals(sItem.planId??'')
                          )
                      )
                  )
              ).build();

              List<DBCXOrderProduct> listProduct = queryProduct.find();
              XLogUtils.printLog("---整单促销,按商品 =${XJsonUtils.obj2Json(listProduct)}, size=${listProduct.length}");
              if (listProduct.isNotEmpty) {
                specIds.add(specId);
              }
            }
          }
          sItem.specIds=[];
          sItem.specIds!.addAll(specIds);

          if(sItem.specIds!.isNotEmpty){
            specidsProductExcl.add(sItem);
          }
        }

        //按分类品牌系列 应用
        for(String sPlanId in planIds){
          BeanOrderItemPromotionSpecIds sItem= BeanOrderItemPromotionSpecIds();
          sItem.planId=sPlanId;
          sItem.excl=false;
          sItem.type=1;

          Set<String> specIds={};

          for(BeanShoppingCartRequestPromotionItems goodItem in items) {
            String specId = goodItem.specId??'';

            //查找品牌拥有的促销
            String brandId=goodItem.brandId??'';
            if(!XStringUtils.isEmpty(brandId)){

              Query<DBCXOrderProduct> queryBrand = box_DBCXOrderProduct!.query(
                  DBCXOrderProduct_.productType.equals('1').and(
                      DBCXOrderProduct_.typeId.equals(brandId).and(
                          DBCXOrderProduct_.excl.equals(sItem.excl??false).and(
                              DBCXOrderProduct_.planId.equals(sItem.planId??'')
                          )
                      )
                  )
              ).build();

              List<DBCXOrderProduct> listBrand=queryBrand.find();
              XLogUtils.printLog("---整单促销,按品牌 =${XJsonUtils.obj2Json(listBrand)}, size=${listBrand.length}");
              if(listBrand.isNotEmpty){
                specIds.add(specId);
              }
              //
            }

            //3.查找系列拥有的促销
            String seriesId=goodItem.seriesId??'';
            if (!XStringUtils.isEmpty(seriesId)){

              Query<DBCXOrderProduct> querySeries = box_DBCXOrderProduct!.query(
                  DBCXOrderProduct_.productType.equals('2').and(
                      DBCXOrderProduct_.typeId.equals(seriesId).and(
                          DBCXOrderProduct_.excl.equals(sItem.excl??false).and(
                              DBCXOrderProduct_.planId.equals(sItem.planId??'')
                          )
                      )
                  )
              ).build();
              List<DBCXOrderProduct> listSeries=querySeries.find();
              XLogUtils.printLog("---整单促销,按系列 =${XJsonUtils.obj2Json(listSeries)}, size=${listSeries.length}");
              if(listSeries.isNotEmpty){
                specIds.add(specId);
              }
            }

            //4.查找分类拥有的促销
            List<String>? llItemtypeids=goodItem.itemTypeIds;
            if(llItemtypeids!=null && llItemtypeids.isNotEmpty){

              Query<DBCXOrderProduct> queryItemtypeids = box_DBCXOrderProduct!.query(
                  DBCXOrderProduct_.productType.equals('0').and(
                      DBCXOrderProduct_.typeId.oneOf(llItemtypeids).and(
                          DBCXOrderProduct_.excl.equals(sItem.excl??false).and(
                              DBCXOrderProduct_.planId.equals(sItem.planId??'')
                          )
                      )
                  )
              ).build();

              List<DBCXOrderProduct> listItemtypeids=queryItemtypeids.find();
              XLogUtils.printLog("---整单促销,按分类 =${XJsonUtils.obj2Json(listItemtypeids)}, size=${listItemtypeids.length}");
              if(listItemtypeids.isNotEmpty){
                specIds.add(specId);
              }
            }

          }
          sItem.specIds=[];
          sItem.specIds!.addAll(specIds);
          if(sItem.specIds!.isNotEmpty){
            specidsGroupApply.add(sItem);
          }

        }

        //按分类品牌系列 排除
        for(String sPlanId in planIds){
          BeanOrderItemPromotionSpecIds sItem= BeanOrderItemPromotionSpecIds();
          sItem.planId=sPlanId;
          sItem.excl=true;
          sItem.type=1;

          Set<String> specIds={};

          for(BeanShoppingCartRequestPromotionItems goodItem in items) {
            String specId = goodItem.specId??'';

            //查找品牌拥有的促销
            String brandId=goodItem.brandId??'';
            if(!XStringUtils.isEmpty(brandId)){

              Query<DBCXOrderProduct> queryBrand = box_DBCXOrderProduct!.query(
                  DBCXOrderProduct_.productType.equals('1').and(
                      DBCXOrderProduct_.typeId.equals(brandId).and(
                          DBCXOrderProduct_.excl.equals(sItem.excl??false).and(
                              DBCXOrderProduct_.planId.equals(sItem.planId??'')
                          )
                      )
                  )
              ).build();

              List<DBCXOrderProduct> listBrand=queryBrand.find();
              XLogUtils.printLog("---整单促销,按品牌 =${XJsonUtils.obj2Json(listBrand)}, size=${listBrand.length}");
              if(listBrand.isNotEmpty){
                specIds.add(specId);
              }
              //
            }

            //3.查找系列拥有的促销
            String seriesId=goodItem.seriesId??'';
            if (!XStringUtils.isEmpty(seriesId)){

              Query<DBCXOrderProduct> querySeries = box_DBCXOrderProduct!.query(
                  DBCXOrderProduct_.productType.equals('2').and(
                      DBCXOrderProduct_.typeId.equals(seriesId).and(
                          DBCXOrderProduct_.excl.equals(sItem.excl??false).and(
                              DBCXOrderProduct_.planId.equals(sItem.planId??'')
                          )
                      )
                  )
              ).build();

              List<DBCXOrderProduct> listSeries=querySeries.find();
              XLogUtils.printLog("---整单促销,按系列 =${XJsonUtils.obj2Json(listSeries)}, size=${listSeries.length}");
              if(listSeries.isNotEmpty){
                specIds.add(specId);
              }
            }

            //4.查找分类拥有的促销
            List<String>? llItemtypeids=goodItem.itemTypeIds;
            if(llItemtypeids!=null && llItemtypeids.isNotEmpty){

              Query<DBCXOrderProduct> queryItemtypeids = box_DBCXOrderProduct!.query(
                  DBCXOrderProduct_.productType.equals('0').and(
                      DBCXOrderProduct_.typeId.oneOf(llItemtypeids).and(
                          DBCXOrderProduct_.excl.equals(sItem.excl??false).and(
                              DBCXOrderProduct_.planId.equals(sItem.planId??'')
                          )
                      )
                  )
              ).build();

              List<DBCXOrderProduct> listItemtypeids=queryItemtypeids.find();
              XLogUtils.printLog("---整单促销,按分类 =${XJsonUtils.obj2Json(listItemtypeids)}, size=${listItemtypeids.length}");
              if(listItemtypeids.isNotEmpty){
                specIds.add(specId);
              }
            }

          }
          sItem.specIds=[];
          sItem.specIds!.addAll(specIds);
          if(sItem.specIds!.isNotEmpty){
            specidsGroupExcl.add(sItem);
          }

        }

        //
        response.specIds_product =specidsProductApply;
        response.specIds_product_excl=specidsProductExcl;
        response.specIds_group =specidsGroupApply;
        response.specIds_group_excl=specidsGroupExcl;

        callback(response.toJson());

      }catch ( e){
        XLogUtils.printLog('---getOrderItemsPromotionSpecIds报错:$e');
        callback(response.toJson());
      }

    });
  }


  //获得订单的所有整单促销
  static void getOrderPromotions(
      XFunctionObjectBoxCallback callback
      ){

    Future((){

      ResponseOrderPromotionJson response= ResponseOrderPromotionJson();
      response.code="-1";

      try{
        response.code="200";
        response.msg="成功";

        //所有订单促销
        Query<DbCXPromotion> queryPromotion=box_DbCXPromotion!.query(
            DbCXPromotion_.planId.notEquals('').and(DbCXPromotion_.planType.equals('P002'))
        ).build();

        List<DbCXPromotion> listPromotion=queryPromotion.find();
        XLogUtils.printLog("---所有订单促销,size=${listPromotion.length}");

        //过滤有效期限
        List<BeanShoppingCartItemPromotionJson> listPromotionTime=[];
        for(DbCXPromotion iitem in listPromotion){
          //按时间过滤
          bool isInTime=true;
          String beginDate=iitem.beginDate??'';
          String endDate=iitem.endDate??'';
          if(!XStringUtils.isEmpty(beginDate) && !XStringUtils.isEmpty(endDate)){
            //init
            isInTime=false;
            try{
              int startTime=int.tryParse(beginDate)??0;
              int endTime=int.tryParse(endDate)??0;
              int now=XDateUtils.getCurrentTime_ms();
              if(now>=startTime && now<=endTime){
                isInTime=true;
              }
            }catch (e){
              XLogUtils.printLog("---startTime/endTime报错");
            }
          }

          if(isInTime){
            //在有效时间内
            BeanShoppingCartItemPromotionJson orderP= BeanShoppingCartItemPromotionJson();
            orderP.projectId=iitem.projectId;
            orderP.version=iitem.version;
            orderP.planId=iitem.planId;
            orderP.planType=iitem.planType;
            orderP.promotion=XJsonUtils.json2Map(iitem.promotionJson);
            listPromotionTime.add(orderP);
          }
        }


        /*
                    适配: 1.先插入增量后插入全量情况; 2.补低版本增量情况
                    避免增量删除了某些规则情况: 同一projectId,只取版本号高的
                     */
        //1.算出每个projectId的最高版本
        Map<String,int> projectidVersion={};
        for(BeanShoppingCartItemPromotionJson iitem in listPromotionTime){
          int? noteVersion=projectidVersion['${iitem.projectId}'];
          if(noteVersion==null){
            projectidVersion['${iitem.projectId}']=iitem.version;
          }else{
            if(noteVersion<iitem.version){
              projectidVersion['${iitem.projectId}']=iitem.version;
            }
          }
        }
        //2.清除每个projectId的低版本促销
        listPromotionTime.removeWhere((BeanShoppingCartItemPromotionJson element){
          int lastVersion=projectidVersion['${element.projectId}']??0;
          if(element.version<lastVersion){
            return true;
          }
          return false;
        });

        //3.去重
        Set<BeanShoppingCartItemPromotionJson> setPromotionjson={};
        setPromotionjson.addAll(listPromotionTime);

        response.orderPromotions=[];
        response.orderPromotions!.addAll(setPromotionjson);

        XLogUtils.printLog("---订单促销,response=${XJsonUtils.obj2Json(response)}");
        //
        callback(response.toJson());

      }catch (e){
        XLogUtils.printLog('---getOrderPromotions报错:$e');
        callback(response.toJson());
      }

    });
  }

//支付兜底///////////////////////////////////////////////////////////////////////////

  static void CreateOrderPayRequest(
      BeanH5OfflinePay request,
      XFunctionObjectBoxCallback callback
      ){

    Future((){
      //

      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(request.fastOrderNo),'收到h5通知创建支付兜底: ${XJsonUtils.obj2Json(request)}');

      Query<BeanOfflinePay> queryBeanofflinepay=box_BeanOfflinePay!.query(
          BeanOfflinePay_.requsetId.equals(request.requsetId??'')
      )
          .build();
      List<BeanOfflinePay> listBeanofflinepay=queryBeanofflinepay.find();
      if(listBeanofflinepay.isEmpty){
        BeanOfflinePay item= BeanOfflinePay();
        item.requsetId=request.requsetId;
        item.fastOrderNo=request.fastOrderNo;
        item.createDateLong=XDateUtils.getTime_ms(dateTime:XDateUtils.getDateTimeWithString(request.creatDate??''));
        item.json=XJsonUtils.obj2Json(request);
        //
        box_BeanOfflinePay!.put(item);

        XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(request.fastOrderNo),'支付兜底,创建成功');

      }else{
        //存在不用创建
        XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(request.fastOrderNo),'支付兜底,不用创建,相同的requsetId已存在');
      }

    });
  }
  static void UpdateOrderPayRequest(
      BeanH5OfflinePay request,
      XFunctionObjectBoxCallback callback
      ){

    Future((){
      //

      Query<BeanOfflinePay> queryBeanofflinepay=box_BeanOfflinePay!.query(
          BeanOfflinePay_.requsetId.equals(request.requsetId??'')
      )
          .build();
      List<BeanOfflinePay> listBeanofflinepay=queryBeanofflinepay.find();

      //更改支付状态
      for(BeanOfflinePay item in listBeanofflinepay){
        String json=item.json??'';

        dynamic obj=XJsonUtils.json2Map(json)??{};
        obj['payStatus']=request.payStatus;
        item.json=XJsonUtils.obj2Json(obj);
      }

      //更新
      box_BeanOfflinePay!.putMany(listBeanofflinepay);

      XAliyunLogUtils.sendLog(RBAliyunLogUtils.getAliyunLogKey_UploadOrder(request.fastOrderNo),'支付兜底,更新成功');

    });
  }
  static void getOrderPayRequest(
      String fastOrderNo,
      XFunctionObjectBoxCallback callback
      ){

    Future((){
      //

      ResponseGetOfflinePay response= ResponseGetOfflinePay();
      response.code="-1";

      try{
        if (XStringUtils.isEmpty(fastOrderNo)
        ){
          response.msg="fastOrderNo不能为空";
          callback(response.toJson());
          return;
        }

        response.code="200";
        response.msg="成功";
        response.fastOrderNo=fastOrderNo;

        //

        Query<BeanOfflinePay> queryBeanofflinepay=box_BeanOfflinePay!.query(
            BeanOfflinePay_.fastOrderNo.equals(fastOrderNo)
        ).build();
        List<BeanOfflinePay> listBeanofflinepay=queryBeanofflinepay.find();

        //排序去重
        Set<BeanOfflinePay> setBeanofflinepay={};
        setBeanofflinepay.addAll(listBeanofflinepay);

        List<dynamic> items =[];
        for(BeanOfflinePay iitem in setBeanofflinepay ){
          String json=iitem.json??'';
          items.add(XJsonUtils.json2Map(json));
        }

        response.items= items;
        //
        callback(response.toJson());

      }catch ( e){
        XLogUtils.printLog('---getOrderPayRequest报错:$e');
        callback(response.toJson());
      }

    });
  }


  //购物车(自助收银)/////////////////////////////////////////////////

  //保存商品到本地购物车(用于非多规格或平铺购物车)
  static void saveToShoppingCart({
    required String xTag,
    required BeanShoppingCartDBGood item, //商品(级别)
    bool isModeAdd = false, //是否追加, 否则覆盖
    XFunctionObjectBoxCallback? onCallback,
  }) {
    Future(() {
      try {
        item.xTag = xTag;
        //
        store?.runInTransaction(TxMode.write, (){
          //
          Query<BeanShoppingCartDBGood> query;
          //
          if(xTag==RBConfigs.Tag_selfService){
            //购物车平铺:自助收银
            query= shoppingCartDBGoodBox!
                .query(BeanShoppingCartDBGood_.xTag.equals(xTag).andAll(
                [
                  BeanShoppingCartDBGood_.itemId.equals(item.itemId ?? ''),
                  BeanShoppingCartDBGood_.specId.equals(item.specId ?? '')
                ]
            )
            ).build();
          }else{
            //购物车多规格折叠
            query= shoppingCartDBGoodBox!
                .query(
                BeanShoppingCartDBGood_.xTag.equals(xTag).and(
                    BeanShoppingCartDBGood_.itemId.equals(item.itemId ?? ''))
            ).build();
          }

          //判断商品是否存在
          List<BeanShoppingCartDBGood> list = query.find();

          double shoppingCartItemMoney = 0.0;
          double shoppingCartItemCount = 0.0;
          double shoppingCartItemBaseCount = 0.0;

          if (list.length == 0) {
            //不存在商品,新增商品

            if (item.currentQuantity == 0 && !item.userTagIsContainZero) {
              //不保留为0的商品
            } else {
              //保存
              item.currentBaseQuantity = (item.currentUnitRate ?? 1.0) * item.currentQuantity;
              item.currentMoney = XNumberUtils.d2d(
                  2, (item.currentUnitRate ?? 1.0) * item.currentQuantity * (item.currentPrice ?? (item.dealPrice ?? 0)));

              shoppingCartDBGoodBox!.put(item);
              shoppingCartItemMoney = item.currentMoney ?? 0.0;
              shoppingCartItemCount = item.currentQuantity;
              shoppingCartItemBaseCount = item.currentBaseQuantity;
            }
          } else {
            //存在
            BeanShoppingCartDBGood goodItem = list[0];
            goodItem.currentPrice = item.currentPrice;
            goodItem.currentUnit = item.currentUnit;
            goodItem.currentUnitRate = item.currentUnitRate;
            goodItem.adjustType = item.adjustType;
            goodItem.adjustTypeListJson = item.adjustTypeListJson;
            goodItem.jsonData=item.jsonData;

            if (isModeAdd) {
              //追加,需重算金额
              goodItem.currentQuantity = goodItem.currentQuantity + item.currentQuantity;
              //唯一码
              if (!XStringUtils.isEmpty(item.uniqueCodeListJson)) {
                List<dynamic> uniqueCodeList = XJsonUtils.json2List(goodItem.uniqueCodeListJson);
                List<dynamic> uniqueCodeList_new = XJsonUtils.json2List(item.uniqueCodeListJson);
                uniqueCodeList.addAll(uniqueCodeList_new);
                goodItem.uniqueCodeListJson = XJsonUtils.obj2Json(uniqueCodeList);
              }
              //批次码
              if (!XStringUtils.isEmpty(item.batchCodeListJson)) {
                List<dynamic> batchCodeList = XJsonUtils.json2List(goodItem.batchCodeListJson);
                List<dynamic> batchCodeList_new = XJsonUtils.json2List(item.batchCodeListJson);
                batchCodeList.addAll(batchCodeList_new);
                goodItem.batchCodeListJson = XJsonUtils.obj2Json(batchCodeList);
              }
            } else {
              //覆盖,需重算金额
              goodItem.currentQuantity = item.currentQuantity;

              //唯一码
              goodItem.uniqueCodeListJson = item.uniqueCodeListJson;
              //批次码
              goodItem.batchCodeListJson = item.batchCodeListJson;
            }

            goodItem.currentBaseQuantity = (goodItem.currentUnitRate ?? 1.0) * goodItem.currentQuantity;
            goodItem.currentMoney = XNumberUtils.d2d(
                2,
                (goodItem.currentUnitRate ?? 1.0) *
                    goodItem.currentQuantity *
                    (goodItem.currentPrice ?? (goodItem.dealPrice ?? 0)));
            //
            if (goodItem.currentQuantity == 0 && !goodItem.userTagIsContainZero) {
              //不保留为0的商品
              shoppingCartDBGoodBox!.remove(goodItem.xid);
            } else {
              shoppingCartDBGoodBox!.put(goodItem);
            }

            shoppingCartItemMoney = goodItem.currentMoney ?? 0.0;
            shoppingCartItemCount = goodItem.currentQuantity;
            shoppingCartItemBaseCount = goodItem.currentBaseQuantity;
          }
          query.close();

          //返回购物车总数量
          if (onCallback != null) {
            double shoppingCartTotalMoney = 0.0;
            double shoppingCartTotalCount = 0.0;
            Query<BeanShoppingCartDBGood> query1 =
            shoppingCartDBGoodBox!.query(BeanShoppingCartDBGood_.xTag.equals(xTag)).build();
            //
            List<BeanShoppingCartDBGood> slist = query1.find();
            for (BeanShoppingCartDBGood iitem in slist) {
              shoppingCartTotalMoney += (iitem.currentMoney ?? 0.0);
              shoppingCartTotalCount += iitem.currentQuantity;
            }
            query1.close();

            Map<String, dynamic> result = {};
            result['shoppingCartTotalMoney'] = XNumberUtils.d2d(2, shoppingCartTotalMoney);
            result['shoppingCartTotalCount'] = XNumberUtils.d2d(3, shoppingCartTotalCount);
            result['shoppingCartItemMoney'] = XNumberUtils.d2d(2, shoppingCartItemMoney);
            result['shoppingCartItemCount'] = XNumberUtils.d2d(3, shoppingCartItemCount);
            result['shoppingCartItemBaseCount'] = XNumberUtils.d2d(3, shoppingCartItemBaseCount); //基本单位数量

            XLogUtils.printLog('---result=$result');

            onCallback(result);
          }

          return "ok";
        });

      } catch (e) {
        XLogUtils.printLog('---saveToShoppingCart,trycatch: $e');
      }
    });
  }

  //保存商品到本地购物车(用于多规格折叠购物车)
  static void saveToShoppingCart_Spec({
    required String xTag,
    required BeanShoppingCartDBGood item, //商品(级别)
    required List<BeanShoppingCartDBGoodSpec> specItems, //规格(级别)
    bool isModeAdd = false, //是否追加, 否则覆盖
    XFunctionObjectBoxCallback? onCallback,
  }) {
    Future(() {
      try {
        item.xTag = xTag;

        //
        store?.runInTransaction(TxMode.write, (){

          //判断商品是否存在
          Query<BeanShoppingCartDBGood> query = shoppingCartDBGoodBox!
              .query(
              BeanShoppingCartDBGood_.xTag.equals(xTag).and(BeanShoppingCartDBGood_.itemId.equals(item.itemId ?? '')))
              .build();

          List<BeanShoppingCartDBGood> itemList = query.find();
          query.close();

          double shoppingCartItemMoney = 0.0;
          double shoppingCartItemCount = 0.0;
          double shoppingCartItemBaseCount = 0.0;
          if (itemList.length == 0) {
            //不存在商品,新增商品和规格

            if (!item.userTagIsContainZero) {
              //不保留为0的商品
              List<BeanShoppingCartDBGoodSpec> specItems_1 = [];
              for (BeanShoppingCartDBGoodSpec specItem in specItems) {
                if (specItem.currentQuantity > 0) {
                  specItem.xTag = xTag;
                  specItem.currentMoney = (specItem.currentUnitRate ?? 1.0) *
                      specItem.currentQuantity *
                      (specItem.currentPrice ?? (specItem.dealPrice ?? 0));
                  specItem.currentBaseQuantity = (specItem.currentUnitRate ?? 1.0) * specItem.currentQuantity;

                  shoppingCartItemCount += specItem.currentQuantity;
                  shoppingCartItemBaseCount += specItem.currentBaseQuantity;
                  shoppingCartItemMoney += (specItem.currentMoney ?? 0.0);
                  specItems_1.add(specItem);
                }
              }
              if (specItems_1.length > 0) {
                item.currentQuantity = shoppingCartItemCount;
                item.currentBaseQuantity = shoppingCartItemBaseCount;
                item.currentMoney = XNumberUtils.d2d(2, shoppingCartItemMoney);
                //保存
                shoppingCartDBGoodBox!.put(item);
                shoppingCartDBGoodSpecBox!.putMany(specItems_1);
              }
            } else {
              //保存为0商品
              for (BeanShoppingCartDBGoodSpec specItem in specItems) {
                specItem.xTag = xTag;
                specItem.currentMoney = (specItem.currentUnitRate ?? 1.0) *
                    specItem.currentQuantity *
                    (specItem.currentPrice ?? (specItem.dealPrice ?? 0));
                specItem.currentBaseQuantity = (specItem.currentUnitRate ?? 1.0) * specItem.currentQuantity;

                //主商品数量是基本单位
                shoppingCartItemCount += specItem.currentQuantity;
                shoppingCartItemBaseCount += specItem.currentBaseQuantity;
                shoppingCartItemMoney += (specItem.currentMoney ?? 0.0);
              }
              item.currentQuantity = shoppingCartItemCount;
              item.currentBaseQuantity = shoppingCartItemBaseCount;
              item.currentMoney = XNumberUtils.d2d(2, shoppingCartItemMoney);
              //保存
              shoppingCartDBGoodBox!.put(item);
              shoppingCartDBGoodSpecBox!.putMany(specItems);
            }
          } else {
            //已存在商品,
            BeanShoppingCartDBGood goodItem = itemList[0];

            //判断规格是否存在
            for (BeanShoppingCartDBGoodSpec specItem in specItems) {
              specItem.xTag = xTag;

              Query<BeanShoppingCartDBGoodSpec> query_spec = shoppingCartDBGoodSpecBox!
                  .query(BeanShoppingCartDBGoodSpec_.xTag.equals(xTag).and(BeanShoppingCartDBGoodSpec_.itemId
                  .equals(specItem.itemId ?? '')
                  .and(BeanShoppingCartDBGoodSpec_.specId.equals(specItem.specId ?? ''))))
                  .build();
              List<BeanShoppingCartDBGoodSpec> specList = query_spec.find();

              if (specList.length != 0) {
                //已存在保存规格
                BeanShoppingCartDBGoodSpec iitem = specList[0];

                iitem.currentPrice = specItem.currentPrice;
                iitem.currentUnit = specItem.currentUnit;
                iitem.currentUnitRate = specItem.currentUnitRate;
                iitem.adjustType = specItem.adjustType;
                iitem.costPrice = specItem.costPrice;
                iitem.adjustTypeListJson = specItem.adjustTypeListJson;

                if (isModeAdd) {
                  //追加
                  iitem.currentQuantity = iitem.currentQuantity + specItem.currentQuantity;
                  //唯一码
                  if (!XStringUtils.isEmpty(specItem.uniqueCodeListJson)) {
                    List<dynamic> uniqueCodeList = XJsonUtils.json2List(iitem.uniqueCodeListJson);
                    List<dynamic> uniqueCodeList_new = XJsonUtils.json2List(specItem.uniqueCodeListJson);
                    uniqueCodeList.addAll(uniqueCodeList_new);
                    iitem.uniqueCodeListJson = XJsonUtils.obj2Json(uniqueCodeList);
                  }
                  //批次码
                  if (!XStringUtils.isEmpty(specItem.batchCodeListJson)) {
                    List<dynamic> batchCodeList = XJsonUtils.json2List(iitem.batchCodeListJson);
                    List<dynamic> batchCodeList_new = XJsonUtils.json2List(specItem.batchCodeListJson);
                    batchCodeList.addAll(batchCodeList_new);
                    iitem.batchCodeListJson = XJsonUtils.obj2Json(batchCodeList);
                  }
                } else {
                  //覆盖
                  iitem.currentQuantity = specItem.currentQuantity;
                  //唯一码
                  iitem.uniqueCodeListJson = specItem.uniqueCodeListJson;
                  //批次码
                  iitem.batchCodeListJson = specItem.batchCodeListJson;
                }
                //

                iitem.currentMoney = XNumberUtils.d2d(
                    2,
                    (iitem.currentUnitRate ?? 1.0) *
                        iitem.currentQuantity *
                        (iitem.currentPrice ?? (iitem.dealPrice ?? 0)));
                iitem.currentBaseQuantity = iitem.currentQuantity * (iitem.currentUnitRate ?? 1.0);

                if (iitem.currentQuantity == 0 && !goodItem.userTagIsContainZero) {
                  //不保存为0规格
                  shoppingCartDBGoodSpecBox!.remove(iitem.xid);
                } else {
                  //保存为0规格
                  shoppingCartDBGoodSpecBox!.put(iitem);
                }
              } else {
                //不存在保存规格
                specItem.currentMoney = XNumberUtils.d2d(
                    2,
                    (specItem.currentUnitRate ?? 1.0) *
                        specItem.currentQuantity *
                        (specItem.currentPrice ?? (specItem.dealPrice ?? 0)));
                specItem.currentBaseQuantity = specItem.currentQuantity * (specItem.currentUnitRate ?? 1.0);

                if (specItem.currentQuantity == 0 && !goodItem.userTagIsContainZero) {
                  //不保存为0规格
                } else {
                  //保存为0规格
                  shoppingCartDBGoodSpecBox!.put(specItem);
                }
              }
              query_spec.close();
            }

            //更新数量(所有规格总数)
            goodItem.currentQuantity = 0.0;
            goodItem.currentBaseQuantity = 0.0;
            goodItem.currentMoney = 0.0;
            Query<BeanShoppingCartDBGoodSpec> query_spec_total = shoppingCartDBGoodSpecBox!
                .query(BeanShoppingCartDBGoodSpec_.xTag
                .equals(xTag)
                .and(BeanShoppingCartDBGoodSpec_.itemId.equals(goodItem.itemId ?? '')))
                .build();
            List<BeanShoppingCartDBGoodSpec> totalSpecList = query_spec_total.find();

            if (totalSpecList.length == 0) {
              //不存在规格,删除商品
              shoppingCartDBGoodBox!.remove(goodItem.xid);
            } else {
              //存在规格
              for (BeanShoppingCartDBGoodSpec it in totalSpecList) {
                //主商品数量是基本单位
                goodItem.currentQuantity = goodItem.currentQuantity + it.currentQuantity;
                goodItem.currentBaseQuantity = goodItem.currentBaseQuantity + it.currentBaseQuantity;
                goodItem.currentMoney = goodItem.currentMoney! + (it.currentMoney ?? 0.0);
              }
              shoppingCartDBGoodBox!.put(goodItem);
            }

            query_spec_total.close();

            shoppingCartItemMoney = XNumberUtils.d2d(2, goodItem.currentMoney ?? 0.0);
            shoppingCartItemCount = goodItem.currentQuantity;
            shoppingCartItemBaseCount = goodItem.currentBaseQuantity;
          }

          if (onCallback != null) {
            Query<BeanShoppingCartDBGood> queryT =
            shoppingCartDBGoodBox!.query(BeanShoppingCartDBGood_.xTag.equals(xTag)).build();
            List<BeanShoppingCartDBGood> slist = queryT.find();
            double shoppingCartTotalMoney = 0.0;
            double shoppingCartTotalCount = 0.0;
            for (BeanShoppingCartDBGood sitem in slist) {
              shoppingCartTotalMoney += (sitem.currentMoney ?? 0.0);
              shoppingCartTotalCount += sitem.currentQuantity;
            }
            queryT.close();
            //
            Map<String, dynamic> result = {};
            result['shoppingCartTotalMoney'] = XNumberUtils.d2d(2, shoppingCartTotalMoney);
            result['shoppingCartTotalCount'] = XNumberUtils.d2d(2, shoppingCartTotalCount);
            result['shoppingCartItemMoney'] = XNumberUtils.d2d(2, shoppingCartItemMoney);
            result['shoppingCartItemCount'] = XNumberUtils.d2d(3, shoppingCartItemCount);
            result['shoppingCartItemBaseCount'] = XNumberUtils.d2d(3, shoppingCartItemBaseCount); //基本单位数量
            onCallback(result);
          }

          return "ok";
        });


      } catch (e) {
        XLogUtils.printLog('saveToShoppingCart_BeanDBGoodSpec,trycatch: $e');
      }
    });
  }

  //获取购物车列表(折叠方式,一起返回规格明细)
  static void getShoppingCartList(
      {
        required String xTag,
        required int pageIndex,
        required int pageSize,
        String? keyword,
        String? itemId, //优先以itemId为准,用于搜索单个商品,如:添加多规格界面使用
        required XFunctionObjectBoxCallback callback}) {
    Future(() {

      Map<String,dynamic> response={};
      response['code']='-1';

      List<ComponentBeanGoodItem> totalList = [];
      List<BeanShoppingCartDBGood> list;

      int shoppingCartItemCount = 0;

      try {
        // 总页数
        int pageCount = 0;

        if (!XStringUtils.isEmpty(itemId)) {
          if (pageIndex < 0 || pageSize <= 0) {
            pageCount = 1;
            pageSize = 20;
          }

          Query<BeanShoppingCartDBGood> query = shoppingCartDBGoodBox!
              .query(BeanShoppingCartDBGood_.xTag.equals(xTag).and(BeanShoppingCartDBGood_.itemId.equals(itemId!)))
              .build(); //

          //计算分页
          shoppingCartItemCount = query.count();
          pageCount = shoppingCartItemCount / pageSize == 0 ? 1 : (shoppingCartItemCount / pageSize).ceil();

          //偏离数=当前页数(第一页从1开始)*每页数量
          int offset = (pageIndex - 1) * pageSize;

          query.limit = pageSize;
          query.offset = offset;
          list = query.find();
          query.close();
        } else {
          if (pageIndex < 0 || pageSize <= 0) {
            callback(response);
            return;
          }

          if (XStringUtils.isEmpty(keyword)) {
            //全部

            //计算分页
            shoppingCartItemCount = shoppingCartDBGoodBox!.count();
            pageCount = shoppingCartItemCount / pageSize == 0 ? 1 : (shoppingCartItemCount / pageSize).ceil();

            //偏离数=当前页数(第一页从1开始)*每页数量
            int offset = (pageIndex - 1) * pageSize;

            //全部分类
            Query<BeanShoppingCartDBGood> query =
            shoppingCartDBGoodBox!.query(BeanShoppingCartDBGood_.xTag.equals(xTag)).build();
            query.limit = pageSize;
            query.offset = offset;
            list = query.find();
            query.close();
          } else {
            //keyword
            /*

             */
            Query<BeanShoppingCartDBGood> query = shoppingCartDBGoodBox!
                .query(BeanShoppingCartDBGood_.xTag.equals(xTag).and(BeanShoppingCartDBGood_.itemName
                .contains(keyword!)
                .or(BeanShoppingCartDBGood_.skuBarcode.contains(keyword).or(BeanShoppingCartDBGood_.itemCode
                .contains(keyword)
                .or(BeanShoppingCartDBGood_.pinyin.contains(keyword))))))
                .build();

            //计算分页
            shoppingCartItemCount = query.count();
            pageCount = shoppingCartItemCount / pageSize == 0 ? 1 : (shoppingCartItemCount / pageSize).ceil();

            //偏离数=当前页数(第一页从1开始)*每页数量
            int offset = (pageIndex - 1) * pageSize;

            query.limit = pageSize;
            query.offset = offset;
            list = query.find();
            query.close();
          }
        }

        double totalMoney = 0; // 总价
        double totalCount = 0; // 总数
        double totalCostMoney = 0; // 总数
        for (BeanShoppingCartDBGood iitem in list) {
          //Map<String, dynamic> map = iitem.toJson();
          // XLogUtils.printLog('---search, iitem.jsonData=${iitem.jsonData}');
          ComponentBeanGoodItem map = RBBusinessUtils.dbBeanToComponentBean(iitem);
          totalMoney += map.currentMoney;
          totalCount += map.currentQuantity;
          totalCostMoney += XNumberUtils.dynamic2double(map.costPrice) ?? 0.0;

          if (RBBusinessUtils.isSpecType(iitem.specType)) {
            //多规格
            List<ComponentBeanGoodItem> currentSpecList = [];

            Query<BeanShoppingCartDBGoodSpec> query_spec_all = shoppingCartDBGoodSpecBox!
                .query(BeanShoppingCartDBGoodSpec_.xTag
                .equals(xTag)
                .and(BeanShoppingCartDBGoodSpec_.itemId.equals(iitem.itemId ?? '')))
                .build();
            List<BeanShoppingCartDBGoodSpec> listS = query_spec_all.find();
            for (BeanShoppingCartDBGoodSpec iitemSpec in listS) {
              // XLogUtils.printLog('iitemSpec.costPrice = ${iitemSpec.costPrice}');
              ComponentBeanGoodItem sBean = RBBusinessUtils.dbSpecBeanToComponentBean(iitemSpec);
              // XLogUtils.printLog('iitemSpec.sBean.costPrice = ${sBean.costPrice}');
              currentSpecList.add(sBean);
            }
            query_spec_all.close();

            map.currentSpecList = currentSpecList;
            totalList.add(map);
          } else {
            //单规格
            totalList.add(map);
          }
        }

        response['code'] = "200";
        response['PageIndex'] = pageIndex;
        response['PageSize'] = pageSize;
        response['PageCount'] = pageCount;
        response['totalCount'] = totalCount;
        response['totalMoney'] = totalMoney;
        response['totalCostMoney'] = totalCostMoney;
        response['items'] = totalList;
        response['shoppingCartItemCount'] = shoppingCartItemCount;

        // String sc_json = XJsonUtils.obj2Json(response);
        // XLogUtils.printLog('---购物车json=$sc_json');
        callback(response);
      } catch (e, st) {
        XLogUtils.printLog('$e,$st');
        response['code'] = "-1";
        callback(response);
      }
    });
  }

  //获取已选的商品列表信息
  static void getShoppingCartInfo(
      {
        required String xTag,
        required XFunctionObjectBoxCallback callback}) {
    Future(() {
      // 返回总数量（shoppingCartItemCount）、总金额（shoppingCartTotalMoney）、商品信息（map<itemId,GoodBeanMap> ）
      Map<String, dynamic> totalMap = {}; //

      try {
        Query<BeanShoppingCartDBGood> query =
        shoppingCartDBGoodBox!.query(BeanShoppingCartDBGood_.xTag.equals(xTag)).build();
        List<BeanShoppingCartDBGood> list = query.find();
        query.close();

        double shoppingCartTotalMoney = 0;
        double shoppingCartTotalCount = 0;
        for (BeanShoppingCartDBGood iitem in list) {
          if (iitem.itemId == null) {
            continue;
          }

          shoppingCartTotalMoney += (iitem.currentMoney ?? 0.0);
          shoppingCartTotalCount += iitem.currentQuantity;
          Map<String, dynamic> map = iitem.toJson();
          if (RBBusinessUtils.isSpecType(iitem.specType)) {
            //多规格
            List<BeanShoppingCartDBGoodSpec> specList = [];

            Query<BeanShoppingCartDBGoodSpec> query_spec_all = shoppingCartDBGoodSpecBox!
                .query(BeanShoppingCartDBGoodSpec_.xTag
                .equals(xTag)
                .and(BeanShoppingCartDBGoodSpec_.itemId.equals(iitem.itemId!)))
                .build();
            List<BeanShoppingCartDBGoodSpec> listS = query_spec_all.find();
            for (BeanShoppingCartDBGoodSpec iitemSpec in listS) {
              specList.add(iitemSpec);
            }
            query_spec_all.close();

            map['currentSpecList'] = specList;
          }

          totalMap[iitem.itemId!] = map;
        }

        totalMap['shoppingCartItemCount'] = list.length;
        totalMap['shoppingCartTotalMoney'] = shoppingCartTotalMoney;
        totalMap['shoppingCartTotalCount'] = shoppingCartTotalCount;

        callback(totalMap);
      } catch (e) {
        XLogUtils.printLog('$e');
        callback(totalMap);
      }
    });
  }

  //删除整个商品(specId==null)或者某个规格
  static void delShoppingCart(
      {required String xTag,
        String? itemId,
        String? specId,
        XFunctionObjectBoxCallback? onCallback}) {
    Future(() {
      try {


        if (itemId == null) {
          //删除全部,清空购物车
          Query<BeanShoppingCartDBGoodSpec> query_spec_all =
          shoppingCartDBGoodSpecBox!.query(BeanShoppingCartDBGoodSpec_.xTag.equals(xTag)).build();
          List<BeanShoppingCartDBGoodSpec> listS = query_spec_all.find();
          List<int> ids_s = [];
          for (BeanShoppingCartDBGoodSpec ss in listS) {
            ids_s.add(ss.xid);
          }

          shoppingCartDBGoodSpecBox!.removeMany(ids_s);
          query_spec_all.close();

          //删除该商品
          Query<BeanShoppingCartDBGood> query_item_all =
          shoppingCartDBGoodBox!.query(BeanShoppingCartDBGood_.xTag.equals(xTag)).build();
          List<BeanShoppingCartDBGood> listI = query_item_all.find();
          List<int> ids_i = [];
          for (BeanShoppingCartDBGood ss in listI) {
            ids_i.add(ss.xid);
          }

          shoppingCartDBGoodBox!.removeMany(ids_i);

          query_item_all.close();

          if (onCallback != null) {
            onCallback({});
          }
        } else {
          Query<BeanShoppingCartDBGood> query = shoppingCartDBGoodBox!
              .query(BeanShoppingCartDBGood_.xTag.equals(xTag).and(BeanShoppingCartDBGood_.itemId.equals(itemId)))
              .build(); //
          List<BeanShoppingCartDBGood> list = query.find();

          if (list.length != 0) {
            BeanShoppingCartDBGood item = list[0];
            Query<BeanShoppingCartDBGoodSpec> query_spec_all = shoppingCartDBGoodSpecBox!
                .query(BeanShoppingCartDBGoodSpec_.xTag
                .equals(xTag)
                .and(BeanShoppingCartDBGoodSpec_.itemId.equals(item.itemId!)))
                .build(); //
            List<BeanShoppingCartDBGoodSpec> listS = query_spec_all.find();

            if (XStringUtils.isEmpty(specId)) {
              List<int> ids = [];
              for (BeanShoppingCartDBGoodSpec s1 in listS) {
                ids.add(s1.xid);
              }
              //删除该商品所有规格
              shoppingCartDBGoodSpecBox!.removeMany(ids);
              //删除该商品
              shoppingCartDBGoodBox!.remove(item.xid);
            } else {
              //删除该商品某个规格
              for (BeanShoppingCartDBGoodSpec s1 in listS) {
                if (specId == s1.specId) {
                  shoppingCartDBGoodSpecBox!.remove(s1.xid);
                  break;
                }
              }
            }

            query_spec_all.close();
          }

          query.close();
          if (onCallback != null) {
            onCallback({});
          }
        }




      } catch (e) {
        XLogUtils.printLog('$e');
        if (onCallback != null) {
          onCallback({});
        }
      }
    });
  }


}